From 02aa3290a37b8757252ea9d20d38b31d73d4d46e Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Mon, 10 Apr 2023 16:52:10 +0200 Subject: [PATCH 01/21] Add project-dir --- action.yml | 4 +- dist/cache-save/index.js | 448 ++++---- dist/setup/index.js | 2236 +++++++++++++++++++------------------- src/cache-utils.ts | 31 +- 4 files changed, 1388 insertions(+), 1331 deletions(-) diff --git a/action.yml b/action.yml index b22de1ef6..9e73a2954 100644 --- a/action.yml +++ b/action.yml @@ -25,7 +25,9 @@ inputs: description: 'Used to specify a package manager for caching in the default directory. Supported values: npm, yarn, pnpm.' cache-dependency-path: description: 'Used to specify the path to a dependency file: package-lock.json, yarn.lock, etc. Supports wildcards or a list of file names for caching multiple dependencies.' -# TODO: add input to control forcing to pull from cloud or dist. + project-dir: + description: 'Optional path used as a current working directory during executing package manager commands. Important if project directory is not the same as root.' +# TODO: add input to control forcing to pull from cloud or dist. # escape valve for someone having issues or needing the absolute latest which isn't cached yet outputs: cache-hit: diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index a260283c4..996806004 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -59126,87 +59126,87 @@ exports.debug = debug; // for test /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.run = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const cache = __importStar(__nccwpck_require__(7799)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const constants_1 = __nccwpck_require__(9042); -const cache_utils_1 = __nccwpck_require__(1678); -// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in -// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to -// throw an uncaught exception. Instead of failing this action, just warn. -process.on('uncaughtException', e => { - const warningPrefix = '[warning]'; - core.info(`${warningPrefix}${e.message}`); -}); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - const cacheLock = core.getInput('cache'); - yield cachePackages(cacheLock); - } - catch (error) { - core.setFailed(error.message); - } - }); -} -exports.run = run; -const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const state = core.getState(constants_1.State.CacheMatchedKey); - const primaryKey = core.getState(constants_1.State.CachePrimaryKey); - const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); - if (!packageManagerInfo) { - core.debug(`Caching for '${packageManager}' is not supported`); - return; - } - const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); - if (!fs_1.default.existsSync(cachePath)) { - throw new Error(`Cache folder path is retrieved for ${packageManager} but doesn't exist on disk: ${cachePath}`); - } - if (primaryKey === state) { - core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`); - return; - } - const cacheId = yield cache.saveCache([cachePath], primaryKey); - if (cacheId == -1) { - return; - } - core.info(`Cache saved with the key: ${primaryKey}`); -}); -run(); + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.run = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const cache = __importStar(__nccwpck_require__(7799)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const constants_1 = __nccwpck_require__(9042); +const cache_utils_1 = __nccwpck_require__(1678); +// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in +// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to +// throw an uncaught exception. Instead of failing this action, just warn. +process.on('uncaughtException', e => { + const warningPrefix = '[warning]'; + core.info(`${warningPrefix}${e.message}`); +}); +function run() { + return __awaiter(this, void 0, void 0, function* () { + try { + const cacheLock = core.getInput('cache'); + yield cachePackages(cacheLock); + } + catch (error) { + core.setFailed(error.message); + } + }); +} +exports.run = run; +const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { + const state = core.getState(constants_1.State.CacheMatchedKey); + const primaryKey = core.getState(constants_1.State.CachePrimaryKey); + const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); + if (!packageManagerInfo) { + core.debug(`Caching for '${packageManager}' is not supported`); + return; + } + const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); + if (!fs_1.default.existsSync(cachePath)) { + throw new Error(`Cache folder path is retrieved for ${packageManager} but doesn't exist on disk: ${cachePath}`); + } + if (primaryKey === state) { + core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`); + return; + } + const cacheId = yield cache.saveCache([cachePath], primaryKey); + if (cacheId == -1) { + return; + } + core.info(`Cache saved with the key: ${primaryKey}`); +}); +run(); /***/ }), @@ -59215,123 +59215,139 @@ run(); /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getCommandOutput = exports.supportedPackageManagers = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const exec = __importStar(__nccwpck_require__(1514)); -const cache = __importStar(__nccwpck_require__(7799)); -exports.supportedPackageManagers = { - npm: { - lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], - getCacheFolderCommand: 'npm config get cache' - }, - pnpm: { - lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path --silent' - }, - yarn1: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn cache dir' - }, - yarn2: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn config get cacheFolder' - } -}; -const getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () { - let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true }); - if (exitCode) { - stderr = !stderr.trim() - ? `The '${toolCommand}' command failed with exit code: ${exitCode}` - : stderr; - throw new Error(stderr); - } - return stdout.trim(); -}); -exports.getCommandOutput = getCommandOutput; -const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`); - if (!stdOut) { - throw new Error(`Could not retrieve version of ${packageManager}`); - } - return stdOut; -}); -const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { - if (packageManager === 'npm') { - return exports.supportedPackageManagers.npm; - } - else if (packageManager === 'pnpm') { - return exports.supportedPackageManagers.pnpm; - } - else if (packageManager === 'yarn') { - const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); - core.debug(`Consumed yarn version is ${yarnVersion}`); - if (yarnVersion.startsWith('1.')) { - return exports.supportedPackageManagers.yarn1; - } - else { - return exports.supportedPackageManagers.yarn2; - } - } - else { - return null; - } -}); -exports.getPackageManagerInfo = getPackageManagerInfo; -const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand); - if (!stdOut) { - throw new Error(`Could not get cache folder path for ${packageManager}`); - } - core.debug(`${packageManager} path is ${stdOut}`); - return stdOut.trim(); -}); -exports.getCacheDirectoryPath = getCacheDirectoryPath; -function isGhes() { - const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; -} -exports.isGhes = isGhes; -function isCacheFeatureAvailable() { - if (cache.isFeatureAvailable()) - return true; - if (isGhes()) { - core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); - return false; - } - core.warning('The runner was not able to contact the cache service. Caching will be skipped'); - return false; -} -exports.isCacheFeatureAvailable = isCacheFeatureAvailable; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const cache = __importStar(__nccwpck_require__(7799)); +const path_1 = __importDefault(__nccwpck_require__(1017)); +exports.supportedPackageManagers = { + npm: { + lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], + getCacheFolderCommand: 'npm config get cache' + }, + pnpm: { + lockFilePatterns: ['pnpm-lock.yaml'], + getCacheFolderCommand: 'pnpm store path --silent' + }, + yarn1: { + lockFilePatterns: ['yarn.lock'], + getCacheFolderCommand: 'yarn cache dir' + }, + yarn2: { + lockFilePatterns: ['yarn.lock'], + getCacheFolderCommand: 'yarn config get cacheFolder' + } +}; +const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, function* () { + let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, Object.assign({ ignoreReturnCode: true }, (cwd !== null && { cwd }))); + if (exitCode) { + stderr = !stderr.trim() + ? `The '${toolCommand}' command failed with exit code: ${exitCode}` + : stderr; + throw new Error(stderr); + } + return stdout.trim(); +}); +exports.getCommandOutput = getCommandOutput; +const getPackageManagerWorkingDir = () => { + const projectDir = core.getInput('project-dir'); + if (projectDir) { + return projectDir; + } + const cache = core.getInput('cache'); + if (cache !== 'yarn') { + return null; + } + const cacheDependencyPath = core.getInput('cache-dependency-path'); + return cacheDependencyPath ? path_1.default.dirname(cacheDependencyPath) : null; +}; +const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`, getPackageManagerWorkingDir()); + if (!stdOut) { + throw new Error(`Could not retrieve version of ${packageManager}`); + } + return stdOut; +}); +const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { + if (packageManager === 'npm') { + return exports.supportedPackageManagers.npm; + } + else if (packageManager === 'pnpm') { + return exports.supportedPackageManagers.pnpm; + } + else if (packageManager === 'yarn') { + const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); + core.debug(`Consumed yarn version is ${yarnVersion}`); + if (yarnVersion.startsWith('1.')) { + return exports.supportedPackageManagers.yarn1; + } + else { + return exports.supportedPackageManagers.yarn2; + } + } + else { + return null; + } +}); +exports.getPackageManagerInfo = getPackageManagerInfo; +const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand, getPackageManagerWorkingDir()); + if (!stdOut) { + throw new Error(`Could not get cache folder path for ${packageManager}`); + } + core.debug(`${packageManager} path is ${stdOut}`); + return stdOut.trim(); +}); +exports.getCacheDirectoryPath = getCacheDirectoryPath; +function isGhes() { + const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +exports.isGhes = isGhes; +function isCacheFeatureAvailable() { + if (cache.isFeatureAvailable()) + return true; + if (isGhes()) { + core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); + return false; + } + core.warning('The runner was not able to contact the cache service. Caching will be skipped'); + return false; +} +exports.isCacheFeatureAvailable = isCacheFeatureAvailable; /***/ }), @@ -59340,24 +59356,24 @@ exports.isCacheFeatureAvailable = isCacheFeatureAvailable; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Outputs = exports.State = exports.LockType = void 0; -var LockType; -(function (LockType) { - LockType["Npm"] = "npm"; - LockType["Pnpm"] = "pnpm"; - LockType["Yarn"] = "yarn"; -})(LockType = exports.LockType || (exports.LockType = {})); -var State; -(function (State) { - State["CachePrimaryKey"] = "CACHE_KEY"; - State["CacheMatchedKey"] = "CACHE_RESULT"; -})(State = exports.State || (exports.State = {})); -var Outputs; -(function (Outputs) { - Outputs["CacheHit"] = "cache-hit"; -})(Outputs = exports.Outputs || (exports.Outputs = {})); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Outputs = exports.State = exports.LockType = void 0; +var LockType; +(function (LockType) { + LockType["Npm"] = "npm"; + LockType["Pnpm"] = "pnpm"; + LockType["Yarn"] = "yarn"; +})(LockType = exports.LockType || (exports.LockType = {})); +var State; +(function (State) { + State["CachePrimaryKey"] = "CACHE_KEY"; + State["CacheMatchedKey"] = "CACHE_RESULT"; +})(State = exports.State || (exports.State = {})); +var Outputs; +(function (Outputs) { + Outputs["CacheHit"] = "cache-hit"; +})(Outputs = exports.Outputs || (exports.Outputs = {})); /***/ }), diff --git a/dist/setup/index.js b/dist/setup/index.js index 51aaaa160..6bc89acf4 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71022,73 +71022,73 @@ function wrappy (fn, cb) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.configAuthentication = void 0; -const fs = __importStar(__nccwpck_require__(7147)); -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const core = __importStar(__nccwpck_require__(2186)); -const github = __importStar(__nccwpck_require__(5438)); -function configAuthentication(registryUrl, alwaysAuth) { - const npmrc = path.resolve(process.env['RUNNER_TEMP'] || process.cwd(), '.npmrc'); - if (!registryUrl.endsWith('/')) { - registryUrl += '/'; - } - writeRegistryToFile(registryUrl, npmrc, alwaysAuth); -} -exports.configAuthentication = configAuthentication; -function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) { - let scope = core.getInput('scope'); - if (!scope && registryUrl.indexOf('npm.pkg.github.com') > -1) { - scope = github.context.repo.owner; - } - if (scope && scope[0] != '@') { - scope = '@' + scope; - } - if (scope) { - scope = scope.toLowerCase() + ':'; - } - core.debug(`Setting auth in ${fileLocation}`); - let newContents = ''; - if (fs.existsSync(fileLocation)) { - const curContents = fs.readFileSync(fileLocation, 'utf8'); - curContents.split(os.EOL).forEach((line) => { - // Add current contents unless they are setting the registry - if (!line.toLowerCase().startsWith(`${scope}registry`)) { - newContents += line + os.EOL; - } - }); - } - // Remove http: or https: from front of registry. - const authString = registryUrl.replace(/(^\w+:|^)/, '') + ':_authToken=${NODE_AUTH_TOKEN}'; - const registryString = `${scope}registry=${registryUrl}`; - const alwaysAuthString = `always-auth=${alwaysAuth}`; - newContents += `${authString}${os.EOL}${registryString}${os.EOL}${alwaysAuthString}`; - fs.writeFileSync(fileLocation, newContents); - core.exportVariable('NPM_CONFIG_USERCONFIG', fileLocation); - // Export empty node_auth_token if didn't exist so npm doesn't complain about not being able to find it - core.exportVariable('NODE_AUTH_TOKEN', process.env.NODE_AUTH_TOKEN || 'XXXXX-XXXXX-XXXXX-XXXXX'); -} + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.configAuthentication = void 0; +const fs = __importStar(__nccwpck_require__(7147)); +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +function configAuthentication(registryUrl, alwaysAuth) { + const npmrc = path.resolve(process.env['RUNNER_TEMP'] || process.cwd(), '.npmrc'); + if (!registryUrl.endsWith('/')) { + registryUrl += '/'; + } + writeRegistryToFile(registryUrl, npmrc, alwaysAuth); +} +exports.configAuthentication = configAuthentication; +function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) { + let scope = core.getInput('scope'); + if (!scope && registryUrl.indexOf('npm.pkg.github.com') > -1) { + scope = github.context.repo.owner; + } + if (scope && scope[0] != '@') { + scope = '@' + scope; + } + if (scope) { + scope = scope.toLowerCase() + ':'; + } + core.debug(`Setting auth in ${fileLocation}`); + let newContents = ''; + if (fs.existsSync(fileLocation)) { + const curContents = fs.readFileSync(fileLocation, 'utf8'); + curContents.split(os.EOL).forEach((line) => { + // Add current contents unless they are setting the registry + if (!line.toLowerCase().startsWith(`${scope}registry`)) { + newContents += line + os.EOL; + } + }); + } + // Remove http: or https: from front of registry. + const authString = registryUrl.replace(/(^\w+:|^)/, '') + ':_authToken=${NODE_AUTH_TOKEN}'; + const registryString = `${scope}registry=${registryUrl}`; + const alwaysAuthString = `always-auth=${alwaysAuth}`; + newContents += `${authString}${os.EOL}${registryString}${os.EOL}${alwaysAuthString}`; + fs.writeFileSync(fileLocation, newContents); + core.exportVariable('NPM_CONFIG_USERCONFIG', fileLocation); + // Export empty node_auth_token if didn't exist so npm doesn't complain about not being able to find it + core.exportVariable('NODE_AUTH_TOKEN', process.env.NODE_AUTH_TOKEN || 'XXXXX-XXXXX-XXXXX-XXXXX'); +} /***/ }), @@ -71097,84 +71097,84 @@ function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.restoreCache = void 0; -const cache = __importStar(__nccwpck_require__(7799)); -const core = __importStar(__nccwpck_require__(2186)); -const glob = __importStar(__nccwpck_require__(8090)); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const constants_1 = __nccwpck_require__(9042); -const cache_utils_1 = __nccwpck_require__(1678); -const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); - if (!packageManagerInfo) { - throw new Error(`Caching for '${packageManager}' is not supported`); - } - const platform = process.env.RUNNER_OS; - const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); - const lockFilePath = cacheDependencyPath - ? cacheDependencyPath - : findLockFile(packageManagerInfo); - const fileHash = yield glob.hashFiles(lockFilePath); - if (!fileHash) { - throw new Error('Some specified paths were not resolved, unable to cache dependencies.'); - } - const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; - core.debug(`primary key is ${primaryKey}`); - core.saveState(constants_1.State.CachePrimaryKey, primaryKey); - const cacheKey = yield cache.restoreCache([cachePath], primaryKey); - core.setOutput('cache-hit', Boolean(cacheKey)); - if (!cacheKey) { - core.info(`${packageManager} cache is not found`); - return; - } - core.saveState(constants_1.State.CacheMatchedKey, cacheKey); - core.info(`Cache restored from key: ${cacheKey}`); -}); -exports.restoreCache = restoreCache; -const findLockFile = (packageManager) => { - const lockFiles = packageManager.lockFilePatterns; - const workspace = process.env.GITHUB_WORKSPACE; - const rootContent = fs_1.default.readdirSync(workspace); - const lockFile = lockFiles.find(item => rootContent.includes(item)); - if (!lockFile) { - throw new Error(`Dependencies lock file is not found in ${workspace}. Supported file patterns: ${lockFiles.toString()}`); - } - return path_1.default.join(workspace, lockFile); -}; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.restoreCache = void 0; +const cache = __importStar(__nccwpck_require__(7799)); +const core = __importStar(__nccwpck_require__(2186)); +const glob = __importStar(__nccwpck_require__(8090)); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const constants_1 = __nccwpck_require__(9042); +const cache_utils_1 = __nccwpck_require__(1678); +const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); + if (!packageManagerInfo) { + throw new Error(`Caching for '${packageManager}' is not supported`); + } + const platform = process.env.RUNNER_OS; + const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); + const lockFilePath = cacheDependencyPath + ? cacheDependencyPath + : findLockFile(packageManagerInfo); + const fileHash = yield glob.hashFiles(lockFilePath); + if (!fileHash) { + throw new Error('Some specified paths were not resolved, unable to cache dependencies.'); + } + const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; + core.debug(`primary key is ${primaryKey}`); + core.saveState(constants_1.State.CachePrimaryKey, primaryKey); + const cacheKey = yield cache.restoreCache([cachePath], primaryKey); + core.setOutput('cache-hit', Boolean(cacheKey)); + if (!cacheKey) { + core.info(`${packageManager} cache is not found`); + return; + } + core.saveState(constants_1.State.CacheMatchedKey, cacheKey); + core.info(`Cache restored from key: ${cacheKey}`); +}); +exports.restoreCache = restoreCache; +const findLockFile = (packageManager) => { + const lockFiles = packageManager.lockFilePatterns; + const workspace = process.env.GITHUB_WORKSPACE; + const rootContent = fs_1.default.readdirSync(workspace); + const lockFile = lockFiles.find(item => rootContent.includes(item)); + if (!lockFile) { + throw new Error(`Dependencies lock file is not found in ${workspace}. Supported file patterns: ${lockFiles.toString()}`); + } + return path_1.default.join(workspace, lockFile); +}; /***/ }), @@ -71183,123 +71183,139 @@ const findLockFile = (packageManager) => { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getCommandOutput = exports.supportedPackageManagers = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const exec = __importStar(__nccwpck_require__(1514)); -const cache = __importStar(__nccwpck_require__(7799)); -exports.supportedPackageManagers = { - npm: { - lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], - getCacheFolderCommand: 'npm config get cache' - }, - pnpm: { - lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path --silent' - }, - yarn1: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn cache dir' - }, - yarn2: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn config get cacheFolder' - } -}; -const getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () { - let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true }); - if (exitCode) { - stderr = !stderr.trim() - ? `The '${toolCommand}' command failed with exit code: ${exitCode}` - : stderr; - throw new Error(stderr); - } - return stdout.trim(); -}); -exports.getCommandOutput = getCommandOutput; -const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`); - if (!stdOut) { - throw new Error(`Could not retrieve version of ${packageManager}`); - } - return stdOut; -}); -const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { - if (packageManager === 'npm') { - return exports.supportedPackageManagers.npm; - } - else if (packageManager === 'pnpm') { - return exports.supportedPackageManagers.pnpm; - } - else if (packageManager === 'yarn') { - const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); - core.debug(`Consumed yarn version is ${yarnVersion}`); - if (yarnVersion.startsWith('1.')) { - return exports.supportedPackageManagers.yarn1; - } - else { - return exports.supportedPackageManagers.yarn2; - } - } - else { - return null; - } -}); -exports.getPackageManagerInfo = getPackageManagerInfo; -const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand); - if (!stdOut) { - throw new Error(`Could not get cache folder path for ${packageManager}`); - } - core.debug(`${packageManager} path is ${stdOut}`); - return stdOut.trim(); -}); -exports.getCacheDirectoryPath = getCacheDirectoryPath; -function isGhes() { - const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; -} -exports.isGhes = isGhes; -function isCacheFeatureAvailable() { - if (cache.isFeatureAvailable()) - return true; - if (isGhes()) { - core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); - return false; - } - core.warning('The runner was not able to contact the cache service. Caching will be skipped'); - return false; -} -exports.isCacheFeatureAvailable = isCacheFeatureAvailable; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const cache = __importStar(__nccwpck_require__(7799)); +const path_1 = __importDefault(__nccwpck_require__(1017)); +exports.supportedPackageManagers = { + npm: { + lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], + getCacheFolderCommand: 'npm config get cache' + }, + pnpm: { + lockFilePatterns: ['pnpm-lock.yaml'], + getCacheFolderCommand: 'pnpm store path --silent' + }, + yarn1: { + lockFilePatterns: ['yarn.lock'], + getCacheFolderCommand: 'yarn cache dir' + }, + yarn2: { + lockFilePatterns: ['yarn.lock'], + getCacheFolderCommand: 'yarn config get cacheFolder' + } +}; +const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, function* () { + let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, Object.assign({ ignoreReturnCode: true }, (cwd !== null && { cwd }))); + if (exitCode) { + stderr = !stderr.trim() + ? `The '${toolCommand}' command failed with exit code: ${exitCode}` + : stderr; + throw new Error(stderr); + } + return stdout.trim(); +}); +exports.getCommandOutput = getCommandOutput; +const getPackageManagerWorkingDir = () => { + const projectDir = core.getInput('project-dir'); + if (projectDir) { + return projectDir; + } + const cache = core.getInput('cache'); + if (cache !== 'yarn') { + return null; + } + const cacheDependencyPath = core.getInput('cache-dependency-path'); + return cacheDependencyPath ? path_1.default.dirname(cacheDependencyPath) : null; +}; +const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`, getPackageManagerWorkingDir()); + if (!stdOut) { + throw new Error(`Could not retrieve version of ${packageManager}`); + } + return stdOut; +}); +const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { + if (packageManager === 'npm') { + return exports.supportedPackageManagers.npm; + } + else if (packageManager === 'pnpm') { + return exports.supportedPackageManagers.pnpm; + } + else if (packageManager === 'yarn') { + const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); + core.debug(`Consumed yarn version is ${yarnVersion}`); + if (yarnVersion.startsWith('1.')) { + return exports.supportedPackageManagers.yarn1; + } + else { + return exports.supportedPackageManagers.yarn2; + } + } + else { + return null; + } +}); +exports.getPackageManagerInfo = getPackageManagerInfo; +const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand, getPackageManagerWorkingDir()); + if (!stdOut) { + throw new Error(`Could not get cache folder path for ${packageManager}`); + } + core.debug(`${packageManager} path is ${stdOut}`); + return stdOut.trim(); +}); +exports.getCacheDirectoryPath = getCacheDirectoryPath; +function isGhes() { + const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +exports.isGhes = isGhes; +function isCacheFeatureAvailable() { + if (cache.isFeatureAvailable()) + return true; + if (isGhes()) { + core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); + return false; + } + core.warning('The runner was not able to contact the cache service. Caching will be skipped'); + return false; +} +exports.isCacheFeatureAvailable = isCacheFeatureAvailable; /***/ }), @@ -71308,24 +71324,24 @@ exports.isCacheFeatureAvailable = isCacheFeatureAvailable; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Outputs = exports.State = exports.LockType = void 0; -var LockType; -(function (LockType) { - LockType["Npm"] = "npm"; - LockType["Pnpm"] = "pnpm"; - LockType["Yarn"] = "yarn"; -})(LockType = exports.LockType || (exports.LockType = {})); -var State; -(function (State) { - State["CachePrimaryKey"] = "CACHE_KEY"; - State["CacheMatchedKey"] = "CACHE_RESULT"; -})(State = exports.State || (exports.State = {})); -var Outputs; -(function (Outputs) { - Outputs["CacheHit"] = "cache-hit"; -})(Outputs = exports.Outputs || (exports.Outputs = {})); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Outputs = exports.State = exports.LockType = void 0; +var LockType; +(function (LockType) { + LockType["Npm"] = "npm"; + LockType["Pnpm"] = "pnpm"; + LockType["Yarn"] = "yarn"; +})(LockType = exports.LockType || (exports.LockType = {})); +var State; +(function (State) { + State["CachePrimaryKey"] = "CACHE_KEY"; + State["CacheMatchedKey"] = "CACHE_RESULT"; +})(State = exports.State || (exports.State = {})); +var Outputs; +(function (Outputs) { + Outputs["CacheHit"] = "cache-hit"; +})(Outputs = exports.Outputs || (exports.Outputs = {})); /***/ }), @@ -71334,73 +71350,73 @@ var Outputs; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tc = __importStar(__nccwpck_require__(7784)); -const semver_1 = __importDefault(__nccwpck_require__(5911)); -const base_distribution_1 = __importDefault(__nccwpck_require__(7)); -class BasePrereleaseNodejs extends base_distribution_1.default { - constructor(nodeInfo) { - super(nodeInfo); - } - findVersionInHostedToolCacheDirectory() { - let toolPath = ''; - const localVersionPaths = tc - .findAllVersions('node', this.nodeInfo.arch) - .filter(i => { - const prerelease = semver_1.default.prerelease(i); - if (!prerelease) { - return false; - } - return prerelease[0].includes(this.distribution); - }); - localVersionPaths.sort(semver_1.default.rcompare); - const localVersion = this.evaluateVersions(localVersionPaths); - if (localVersion) { - toolPath = tc.find('node', localVersion, this.nodeInfo.arch); - } - return toolPath; - } - validRange(versionSpec) { - let range; - const [raw, prerelease] = this.splitVersionSpec(versionSpec); - const isValidVersion = semver_1.default.valid(raw); - const rawVersion = (isValidVersion ? raw : semver_1.default.coerce(raw)); - if (prerelease !== this.distribution) { - range = versionSpec; - } - else { - range = `${semver_1.default.validRange(`^${rawVersion}-${this.distribution}`)}-0`; - } - return { range, options: { includePrerelease: !isValidVersion } }; - } - splitVersionSpec(versionSpec) { - return versionSpec.split(/-(.*)/s); - } -} -exports["default"] = BasePrereleaseNodejs; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tc = __importStar(__nccwpck_require__(7784)); +const semver_1 = __importDefault(__nccwpck_require__(5911)); +const base_distribution_1 = __importDefault(__nccwpck_require__(7)); +class BasePrereleaseNodejs extends base_distribution_1.default { + constructor(nodeInfo) { + super(nodeInfo); + } + findVersionInHostedToolCacheDirectory() { + let toolPath = ''; + const localVersionPaths = tc + .findAllVersions('node', this.nodeInfo.arch) + .filter(i => { + const prerelease = semver_1.default.prerelease(i); + if (!prerelease) { + return false; + } + return prerelease[0].includes(this.distribution); + }); + localVersionPaths.sort(semver_1.default.rcompare); + const localVersion = this.evaluateVersions(localVersionPaths); + if (localVersion) { + toolPath = tc.find('node', localVersion, this.nodeInfo.arch); + } + return toolPath; + } + validRange(versionSpec) { + let range; + const [raw, prerelease] = this.splitVersionSpec(versionSpec); + const isValidVersion = semver_1.default.valid(raw); + const rawVersion = (isValidVersion ? raw : semver_1.default.coerce(raw)); + if (prerelease !== this.distribution) { + range = versionSpec; + } + else { + range = `${semver_1.default.validRange(`^${rawVersion}-${this.distribution}`)}-0`; + } + return { range, options: { includePrerelease: !isValidVersion } }; + } + splitVersionSpec(versionSpec) { + return versionSpec.split(/-(.*)/s); + } +} +exports["default"] = BasePrereleaseNodejs; /***/ }), @@ -71409,275 +71425,275 @@ exports["default"] = BasePrereleaseNodejs; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tc = __importStar(__nccwpck_require__(7784)); -const hc = __importStar(__nccwpck_require__(9925)); -const core = __importStar(__nccwpck_require__(2186)); -const io = __importStar(__nccwpck_require__(7436)); -const semver_1 = __importDefault(__nccwpck_require__(5911)); -const assert = __importStar(__nccwpck_require__(9491)); -const path = __importStar(__nccwpck_require__(1017)); -const os_1 = __importDefault(__nccwpck_require__(2037)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -class BaseDistribution { - constructor(nodeInfo) { - this.nodeInfo = nodeInfo; - this.osPlat = os_1.default.platform(); - this.httpClient = new hc.HttpClient('setup-node', [], { - allowRetries: true, - maxRetries: 3 - }); - } - setupNodeJs() { - return __awaiter(this, void 0, void 0, function* () { - let nodeJsVersions; - if (this.nodeInfo.checkLatest) { - const evaluatedVersion = yield this.findVersionInDist(nodeJsVersions); - this.nodeInfo.versionSpec = evaluatedVersion; - } - let toolPath = this.findVersionInHostedToolCacheDirectory(); - if (toolPath) { - core.info(`Found in cache @ ${toolPath}`); - } - else { - const evaluatedVersion = yield this.findVersionInDist(nodeJsVersions); - const toolName = this.getNodejsDistInfo(evaluatedVersion); - toolPath = yield this.downloadNodejs(toolName); - } - if (this.osPlat != 'win32') { - toolPath = path.join(toolPath, 'bin'); - } - core.addPath(toolPath); - }); - } - findVersionInDist(nodeJsVersions) { - return __awaiter(this, void 0, void 0, function* () { - if (!nodeJsVersions) { - nodeJsVersions = yield this.getNodeJsVersions(); - } - const versions = this.filterVersions(nodeJsVersions); - const evaluatedVersion = this.evaluateVersions(versions); - if (!evaluatedVersion) { - throw new Error(`Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`); - } - return evaluatedVersion; - }); - } - evaluateVersions(versions) { - let version = ''; - const { range, options } = this.validRange(this.nodeInfo.versionSpec); - core.debug(`evaluating ${versions.length} versions`); - for (const potential of versions) { - const satisfied = semver_1.default.satisfies(potential, range, options); - if (satisfied) { - version = potential; - break; - } - } - if (version) { - core.debug(`matched: ${version}`); - } - else { - core.debug('match not found'); - } - return version; - } - findVersionInHostedToolCacheDirectory() { - return tc.find('node', this.nodeInfo.versionSpec, this.nodeInfo.arch); - } - getNodeJsVersions() { - return __awaiter(this, void 0, void 0, function* () { - const initialUrl = this.getDistributionUrl(); - const dataUrl = `${initialUrl}/index.json`; - const response = yield this.httpClient.getJson(dataUrl); - return response.result || []; - }); - } - getNodejsDistInfo(version) { - const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); - version = semver_1.default.clean(version) || ''; - const fileName = this.osPlat == 'win32' - ? `node-v${version}-win-${osArch}` - : `node-v${version}-${this.osPlat}-${osArch}`; - const urlFileName = this.osPlat == 'win32' ? `${fileName}.7z` : `${fileName}.tar.gz`; - const initialUrl = this.getDistributionUrl(); - const url = `${initialUrl}/v${version}/${urlFileName}`; - return { - downloadUrl: url, - resolvedVersion: version, - arch: osArch, - fileName: fileName - }; - } - downloadNodejs(info) { - return __awaiter(this, void 0, void 0, function* () { - let downloadPath = ''; - core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`); - try { - downloadPath = yield tc.downloadTool(info.downloadUrl); - } - catch (err) { - if (err instanceof tc.HTTPError && - err.httpStatusCode == 404 && - this.osPlat == 'win32') { - return yield this.acquireWindowsNodeFromFallbackLocation(info.resolvedVersion, info.arch); - } - throw err; - } - const toolPath = yield this.extractArchive(downloadPath, info); - core.info('Done'); - return toolPath; - }); - } - validRange(versionSpec) { - var _a; - let options; - const c = semver_1.default.clean(versionSpec) || ''; - const valid = (_a = semver_1.default.valid(c)) !== null && _a !== void 0 ? _a : versionSpec; - return { range: valid, options }; - } - acquireWindowsNodeFromFallbackLocation(version, arch = os_1.default.arch()) { - return __awaiter(this, void 0, void 0, function* () { - const initialUrl = this.getDistributionUrl(); - const osArch = this.translateArchToDistUrl(arch); - // Create temporary folder to download in to - const tempDownloadFolder = 'temp_' + Math.floor(Math.random() * 2000000000); - const tempDirectory = process.env['RUNNER_TEMP'] || ''; - assert.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); - const tempDir = path.join(tempDirectory, tempDownloadFolder); - yield io.mkdirP(tempDir); - let exeUrl; - let libUrl; - try { - exeUrl = `${initialUrl}/v${version}/win-${osArch}/node.exe`; - libUrl = `${initialUrl}/v${version}/win-${osArch}/node.lib`; - core.info(`Downloading only node binary from ${exeUrl}`); - const exePath = yield tc.downloadTool(exeUrl); - yield io.cp(exePath, path.join(tempDir, 'node.exe')); - const libPath = yield tc.downloadTool(libUrl); - yield io.cp(libPath, path.join(tempDir, 'node.lib')); - } - catch (err) { - if (err instanceof tc.HTTPError && err.httpStatusCode == 404) { - exeUrl = `${initialUrl}/v${version}/node.exe`; - libUrl = `${initialUrl}/v${version}/node.lib`; - const exePath = yield tc.downloadTool(exeUrl); - yield io.cp(exePath, path.join(tempDir, 'node.exe')); - const libPath = yield tc.downloadTool(libUrl); - yield io.cp(libPath, path.join(tempDir, 'node.lib')); - } - else { - throw err; - } - } - const toolPath = yield tc.cacheDir(tempDir, 'node', version, arch); - return toolPath; - }); - } - extractArchive(downloadPath, info) { - return __awaiter(this, void 0, void 0, function* () { - // - // Extract - // - core.info('Extracting ...'); - let extPath; - info = info || {}; // satisfy compiler, never null when reaches here - if (this.osPlat == 'win32') { - const _7zPath = path.join(__dirname, '../..', 'externals', '7zr.exe'); - extPath = yield tc.extract7z(downloadPath, undefined, _7zPath); - // 7z extracts to folder matching file name - const nestedPath = path.join(extPath, path.basename(info.fileName, '.7z')); - if (fs_1.default.existsSync(nestedPath)) { - extPath = nestedPath; - } - } - else { - extPath = yield tc.extractTar(downloadPath, undefined, [ - 'xz', - '--strip', - '1' - ]); - } - // - // Install into the local tool cache - node extracts with a root folder that matches the fileName downloaded - // - core.info('Adding to the cache ...'); - const toolPath = yield tc.cacheDir(extPath, 'node', info.resolvedVersion, info.arch); - return toolPath; - }); - } - getDistFileName() { - const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); - // node offers a json list of versions - let dataFileName; - switch (this.osPlat) { - case 'linux': - dataFileName = `linux-${osArch}`; - break; - case 'darwin': - dataFileName = `osx-${osArch}-tar`; - break; - case 'win32': - dataFileName = `win-${osArch}-exe`; - break; - default: - throw new Error(`Unexpected OS '${this.osPlat}'`); - } - return dataFileName; - } - filterVersions(nodeJsVersions) { - const versions = []; - const dataFileName = this.getDistFileName(); - nodeJsVersions.forEach((nodeVersion) => { - // ensure this version supports your os and platform - if (nodeVersion.files.indexOf(dataFileName) >= 0) { - versions.push(nodeVersion.version); - } - }); - return versions.sort(semver_1.default.rcompare); - } - translateArchToDistUrl(arch) { - switch (arch) { - case 'arm': - return 'armv7l'; - default: - return arch; - } - } -} -exports["default"] = BaseDistribution; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tc = __importStar(__nccwpck_require__(7784)); +const hc = __importStar(__nccwpck_require__(9925)); +const core = __importStar(__nccwpck_require__(2186)); +const io = __importStar(__nccwpck_require__(7436)); +const semver_1 = __importDefault(__nccwpck_require__(5911)); +const assert = __importStar(__nccwpck_require__(9491)); +const path = __importStar(__nccwpck_require__(1017)); +const os_1 = __importDefault(__nccwpck_require__(2037)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +class BaseDistribution { + constructor(nodeInfo) { + this.nodeInfo = nodeInfo; + this.osPlat = os_1.default.platform(); + this.httpClient = new hc.HttpClient('setup-node', [], { + allowRetries: true, + maxRetries: 3 + }); + } + setupNodeJs() { + return __awaiter(this, void 0, void 0, function* () { + let nodeJsVersions; + if (this.nodeInfo.checkLatest) { + const evaluatedVersion = yield this.findVersionInDist(nodeJsVersions); + this.nodeInfo.versionSpec = evaluatedVersion; + } + let toolPath = this.findVersionInHostedToolCacheDirectory(); + if (toolPath) { + core.info(`Found in cache @ ${toolPath}`); + } + else { + const evaluatedVersion = yield this.findVersionInDist(nodeJsVersions); + const toolName = this.getNodejsDistInfo(evaluatedVersion); + toolPath = yield this.downloadNodejs(toolName); + } + if (this.osPlat != 'win32') { + toolPath = path.join(toolPath, 'bin'); + } + core.addPath(toolPath); + }); + } + findVersionInDist(nodeJsVersions) { + return __awaiter(this, void 0, void 0, function* () { + if (!nodeJsVersions) { + nodeJsVersions = yield this.getNodeJsVersions(); + } + const versions = this.filterVersions(nodeJsVersions); + const evaluatedVersion = this.evaluateVersions(versions); + if (!evaluatedVersion) { + throw new Error(`Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`); + } + return evaluatedVersion; + }); + } + evaluateVersions(versions) { + let version = ''; + const { range, options } = this.validRange(this.nodeInfo.versionSpec); + core.debug(`evaluating ${versions.length} versions`); + for (const potential of versions) { + const satisfied = semver_1.default.satisfies(potential, range, options); + if (satisfied) { + version = potential; + break; + } + } + if (version) { + core.debug(`matched: ${version}`); + } + else { + core.debug('match not found'); + } + return version; + } + findVersionInHostedToolCacheDirectory() { + return tc.find('node', this.nodeInfo.versionSpec, this.nodeInfo.arch); + } + getNodeJsVersions() { + return __awaiter(this, void 0, void 0, function* () { + const initialUrl = this.getDistributionUrl(); + const dataUrl = `${initialUrl}/index.json`; + const response = yield this.httpClient.getJson(dataUrl); + return response.result || []; + }); + } + getNodejsDistInfo(version) { + const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); + version = semver_1.default.clean(version) || ''; + const fileName = this.osPlat == 'win32' + ? `node-v${version}-win-${osArch}` + : `node-v${version}-${this.osPlat}-${osArch}`; + const urlFileName = this.osPlat == 'win32' ? `${fileName}.7z` : `${fileName}.tar.gz`; + const initialUrl = this.getDistributionUrl(); + const url = `${initialUrl}/v${version}/${urlFileName}`; + return { + downloadUrl: url, + resolvedVersion: version, + arch: osArch, + fileName: fileName + }; + } + downloadNodejs(info) { + return __awaiter(this, void 0, void 0, function* () { + let downloadPath = ''; + core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`); + try { + downloadPath = yield tc.downloadTool(info.downloadUrl); + } + catch (err) { + if (err instanceof tc.HTTPError && + err.httpStatusCode == 404 && + this.osPlat == 'win32') { + return yield this.acquireWindowsNodeFromFallbackLocation(info.resolvedVersion, info.arch); + } + throw err; + } + const toolPath = yield this.extractArchive(downloadPath, info); + core.info('Done'); + return toolPath; + }); + } + validRange(versionSpec) { + var _a; + let options; + const c = semver_1.default.clean(versionSpec) || ''; + const valid = (_a = semver_1.default.valid(c)) !== null && _a !== void 0 ? _a : versionSpec; + return { range: valid, options }; + } + acquireWindowsNodeFromFallbackLocation(version, arch = os_1.default.arch()) { + return __awaiter(this, void 0, void 0, function* () { + const initialUrl = this.getDistributionUrl(); + const osArch = this.translateArchToDistUrl(arch); + // Create temporary folder to download in to + const tempDownloadFolder = 'temp_' + Math.floor(Math.random() * 2000000000); + const tempDirectory = process.env['RUNNER_TEMP'] || ''; + assert.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); + const tempDir = path.join(tempDirectory, tempDownloadFolder); + yield io.mkdirP(tempDir); + let exeUrl; + let libUrl; + try { + exeUrl = `${initialUrl}/v${version}/win-${osArch}/node.exe`; + libUrl = `${initialUrl}/v${version}/win-${osArch}/node.lib`; + core.info(`Downloading only node binary from ${exeUrl}`); + const exePath = yield tc.downloadTool(exeUrl); + yield io.cp(exePath, path.join(tempDir, 'node.exe')); + const libPath = yield tc.downloadTool(libUrl); + yield io.cp(libPath, path.join(tempDir, 'node.lib')); + } + catch (err) { + if (err instanceof tc.HTTPError && err.httpStatusCode == 404) { + exeUrl = `${initialUrl}/v${version}/node.exe`; + libUrl = `${initialUrl}/v${version}/node.lib`; + const exePath = yield tc.downloadTool(exeUrl); + yield io.cp(exePath, path.join(tempDir, 'node.exe')); + const libPath = yield tc.downloadTool(libUrl); + yield io.cp(libPath, path.join(tempDir, 'node.lib')); + } + else { + throw err; + } + } + const toolPath = yield tc.cacheDir(tempDir, 'node', version, arch); + return toolPath; + }); + } + extractArchive(downloadPath, info) { + return __awaiter(this, void 0, void 0, function* () { + // + // Extract + // + core.info('Extracting ...'); + let extPath; + info = info || {}; // satisfy compiler, never null when reaches here + if (this.osPlat == 'win32') { + const _7zPath = path.join(__dirname, '../..', 'externals', '7zr.exe'); + extPath = yield tc.extract7z(downloadPath, undefined, _7zPath); + // 7z extracts to folder matching file name + const nestedPath = path.join(extPath, path.basename(info.fileName, '.7z')); + if (fs_1.default.existsSync(nestedPath)) { + extPath = nestedPath; + } + } + else { + extPath = yield tc.extractTar(downloadPath, undefined, [ + 'xz', + '--strip', + '1' + ]); + } + // + // Install into the local tool cache - node extracts with a root folder that matches the fileName downloaded + // + core.info('Adding to the cache ...'); + const toolPath = yield tc.cacheDir(extPath, 'node', info.resolvedVersion, info.arch); + return toolPath; + }); + } + getDistFileName() { + const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); + // node offers a json list of versions + let dataFileName; + switch (this.osPlat) { + case 'linux': + dataFileName = `linux-${osArch}`; + break; + case 'darwin': + dataFileName = `osx-${osArch}-tar`; + break; + case 'win32': + dataFileName = `win-${osArch}-exe`; + break; + default: + throw new Error(`Unexpected OS '${this.osPlat}'`); + } + return dataFileName; + } + filterVersions(nodeJsVersions) { + const versions = []; + const dataFileName = this.getDistFileName(); + nodeJsVersions.forEach((nodeVersion) => { + // ensure this version supports your os and platform + if (nodeVersion.files.indexOf(dataFileName) >= 0) { + versions.push(nodeVersion.version); + } + }); + return versions.sort(semver_1.default.rcompare); + } + translateArchToDistUrl(arch) { + switch (arch) { + case 'arm': + return 'armv7l'; + default: + return arch; + } + } +} +exports["default"] = BaseDistribution; /***/ }), @@ -71686,41 +71702,41 @@ exports["default"] = BaseDistribution; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getNodejsDistribution = void 0; -const nightly_builds_1 = __importDefault(__nccwpck_require__(7127)); -const official_builds_1 = __importDefault(__nccwpck_require__(7854)); -const rc_builds_1 = __importDefault(__nccwpck_require__(8837)); -const canary_builds_1 = __importDefault(__nccwpck_require__(969)); -var Distributions; -(function (Distributions) { - Distributions["DEFAULT"] = ""; - Distributions["CANARY"] = "v8-canary"; - Distributions["NIGHTLY"] = "nightly"; - Distributions["RC"] = "rc"; -})(Distributions || (Distributions = {})); -function getNodejsDistribution(installerOptions) { - const versionSpec = installerOptions.versionSpec; - let distribution; - if (versionSpec.includes(Distributions.NIGHTLY)) { - distribution = new nightly_builds_1.default(installerOptions); - } - else if (versionSpec.includes(Distributions.CANARY)) { - distribution = new canary_builds_1.default(installerOptions); - } - else if (versionSpec.includes(Distributions.RC)) { - distribution = new rc_builds_1.default(installerOptions); - } - else { - distribution = new official_builds_1.default(installerOptions); - } - return distribution; -} -exports.getNodejsDistribution = getNodejsDistribution; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getNodejsDistribution = void 0; +const nightly_builds_1 = __importDefault(__nccwpck_require__(7127)); +const official_builds_1 = __importDefault(__nccwpck_require__(7854)); +const rc_builds_1 = __importDefault(__nccwpck_require__(8837)); +const canary_builds_1 = __importDefault(__nccwpck_require__(969)); +var Distributions; +(function (Distributions) { + Distributions["DEFAULT"] = ""; + Distributions["CANARY"] = "v8-canary"; + Distributions["NIGHTLY"] = "nightly"; + Distributions["RC"] = "rc"; +})(Distributions || (Distributions = {})); +function getNodejsDistribution(installerOptions) { + const versionSpec = installerOptions.versionSpec; + let distribution; + if (versionSpec.includes(Distributions.NIGHTLY)) { + distribution = new nightly_builds_1.default(installerOptions); + } + else if (versionSpec.includes(Distributions.CANARY)) { + distribution = new canary_builds_1.default(installerOptions); + } + else if (versionSpec.includes(Distributions.RC)) { + distribution = new rc_builds_1.default(installerOptions); + } + else { + distribution = new official_builds_1.default(installerOptions); + } + return distribution; +} +exports.getNodejsDistribution = getNodejsDistribution; /***/ }), @@ -71729,227 +71745,227 @@ exports.getNodejsDistribution = getNodejsDistribution; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const base_distribution_prerelease_1 = __importDefault(__nccwpck_require__(957)); -class NightlyNodejs extends base_distribution_prerelease_1.default { - constructor(nodeInfo) { - super(nodeInfo); - this.distribution = 'nightly'; - } - getDistributionUrl() { - return 'https://nodejs.org/download/nightly'; - } -} -exports["default"] = NightlyNodejs; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const base_distribution_prerelease_1 = __importDefault(__nccwpck_require__(957)); +class NightlyNodejs extends base_distribution_prerelease_1.default { + constructor(nodeInfo) { + super(nodeInfo); + this.distribution = 'nightly'; + } + getDistributionUrl() { + return 'https://nodejs.org/download/nightly'; + } +} +exports["default"] = NightlyNodejs; /***/ }), /***/ 7854: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(2186)); -const tc = __importStar(__nccwpck_require__(7784)); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const base_distribution_1 = __importDefault(__nccwpck_require__(7)); -class OfficialBuilds extends base_distribution_1.default { - constructor(nodeInfo) { - super(nodeInfo); - } - setupNodeJs() { - return __awaiter(this, void 0, void 0, function* () { - let manifest; - let nodeJsVersions; - const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); - if (this.isLtsAlias(this.nodeInfo.versionSpec)) { - core.info('Attempt to resolve LTS alias from manifest...'); - // No try-catch since it's not possible to resolve LTS alias without manifest - manifest = yield this.getManifest(); - this.nodeInfo.versionSpec = this.resolveLtsAliasFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, manifest); - } - if (this.isLatestSyntax(this.nodeInfo.versionSpec)) { - nodeJsVersions = yield this.getNodeJsVersions(); - const versions = this.filterVersions(nodeJsVersions); - this.nodeInfo.versionSpec = this.evaluateVersions(versions); - core.info('getting latest node version...'); - } - if (this.nodeInfo.checkLatest) { - core.info('Attempt to resolve the latest version from manifest...'); - const resolvedVersion = yield this.resolveVersionFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest); - if (resolvedVersion) { - this.nodeInfo.versionSpec = resolvedVersion; - core.info(`Resolved as '${resolvedVersion}'`); - } - else { - core.info(`Failed to resolve version ${this.nodeInfo.versionSpec} from manifest`); - } - } - let toolPath = this.findVersionInHostedToolCacheDirectory(); - if (toolPath) { - core.info(`Found in cache @ ${toolPath}`); - } - else { - let downloadPath = ''; - try { - core.info(`Attempting to download ${this.nodeInfo.versionSpec}...`); - const versionInfo = yield this.getInfoFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest); - if (versionInfo) { - core.info(`Acquiring ${versionInfo.resolvedVersion} - ${versionInfo.arch} from ${versionInfo.downloadUrl}`); - downloadPath = yield tc.downloadTool(versionInfo.downloadUrl, undefined, this.nodeInfo.auth); - if (downloadPath) { - toolPath = yield this.extractArchive(downloadPath, versionInfo); - } - } - else { - core.info('Not found in manifest. Falling back to download directly from Node'); - } - } - catch (err) { - // Rate limit? - if (err instanceof tc.HTTPError && - (err.httpStatusCode === 403 || err.httpStatusCode === 429)) { - core.info(`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`); - } - else { - core.info(err.message); - } - core.debug(err.stack); - core.info('Falling back to download directly from Node'); - } - if (!toolPath) { - const nodeJsVersions = yield this.getNodeJsVersions(); - const versions = this.filterVersions(nodeJsVersions); - const evaluatedVersion = this.evaluateVersions(versions); - if (!evaluatedVersion) { - throw new Error(`Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`); - } - const toolName = this.getNodejsDistInfo(evaluatedVersion); - toolPath = yield this.downloadNodejs(toolName); - } - } - if (this.osPlat != 'win32') { - toolPath = path_1.default.join(toolPath, 'bin'); - } - core.addPath(toolPath); - }); - } - evaluateVersions(versions) { - let version = ''; - if (this.isLatestSyntax(this.nodeInfo.versionSpec)) { - core.info(`getting latest node version...`); - return versions[0]; - } - version = super.evaluateVersions(versions); - return version; - } - getDistributionUrl() { - return `https://nodejs.org/dist`; - } - getManifest() { - core.debug('Getting manifest from actions/node-versions@main'); - return tc.getManifestFromRepo('actions', 'node-versions', this.nodeInfo.auth, 'main'); - } - resolveLtsAliasFromManifest(versionSpec, stable, manifest) { - var _a; - const alias = (_a = versionSpec.split('lts/')[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); - if (!alias) { - throw new Error(`Unable to parse LTS alias for Node version '${versionSpec}'`); - } - core.debug(`LTS alias '${alias}' for Node version '${versionSpec}'`); - // Supported formats are `lts/`, `lts/*`, and `lts/-n`. Where asterisk means highest possible LTS and -n means the nth-highest. - const n = Number(alias); - const aliases = Object.fromEntries(manifest - .filter(x => x.lts && x.stable === stable) - .map(x => [x.lts.toLowerCase(), x]) - .reverse()); - const numbered = Object.values(aliases); - const release = alias === '*' - ? numbered[numbered.length - 1] - : n < 0 - ? numbered[numbered.length - 1 + n] - : aliases[alias]; - if (!release) { - throw new Error(`Unable to find LTS release '${alias}' for Node version '${versionSpec}'.`); - } - core.debug(`Found LTS release '${release.version}' for Node version '${versionSpec}'`); - return release.version.split('.')[0]; - } - resolveVersionFromManifest(versionSpec, stable, osArch, manifest) { - return __awaiter(this, void 0, void 0, function* () { - try { - const info = yield this.getInfoFromManifest(versionSpec, stable, osArch, manifest); - return info === null || info === void 0 ? void 0 : info.resolvedVersion; - } - catch (err) { - core.info('Unable to resolve version from manifest...'); - core.debug(err.message); - } - }); - } - getInfoFromManifest(versionSpec, stable, osArch, manifest) { - return __awaiter(this, void 0, void 0, function* () { - let info = null; - if (!manifest) { - core.debug('No manifest cached'); - manifest = yield this.getManifest(); - } - const rel = yield tc.findFromManifest(versionSpec, stable, manifest, osArch); - if (rel && rel.files.length > 0) { - info = {}; - info.resolvedVersion = rel.version; - info.arch = rel.files[0].arch; - info.downloadUrl = rel.files[0].download_url; - info.fileName = rel.files[0].filename; - } - return info; - }); - } - isLtsAlias(versionSpec) { - return versionSpec.startsWith('lts/'); - } - isLatestSyntax(versionSpec) { - return ['current', 'latest', 'node'].includes(versionSpec); - } -} -exports["default"] = OfficialBuilds; +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const tc = __importStar(__nccwpck_require__(7784)); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const base_distribution_1 = __importDefault(__nccwpck_require__(7)); +class OfficialBuilds extends base_distribution_1.default { + constructor(nodeInfo) { + super(nodeInfo); + } + setupNodeJs() { + return __awaiter(this, void 0, void 0, function* () { + let manifest; + let nodeJsVersions; + const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); + if (this.isLtsAlias(this.nodeInfo.versionSpec)) { + core.info('Attempt to resolve LTS alias from manifest...'); + // No try-catch since it's not possible to resolve LTS alias without manifest + manifest = yield this.getManifest(); + this.nodeInfo.versionSpec = this.resolveLtsAliasFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, manifest); + } + if (this.isLatestSyntax(this.nodeInfo.versionSpec)) { + nodeJsVersions = yield this.getNodeJsVersions(); + const versions = this.filterVersions(nodeJsVersions); + this.nodeInfo.versionSpec = this.evaluateVersions(versions); + core.info('getting latest node version...'); + } + if (this.nodeInfo.checkLatest) { + core.info('Attempt to resolve the latest version from manifest...'); + const resolvedVersion = yield this.resolveVersionFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest); + if (resolvedVersion) { + this.nodeInfo.versionSpec = resolvedVersion; + core.info(`Resolved as '${resolvedVersion}'`); + } + else { + core.info(`Failed to resolve version ${this.nodeInfo.versionSpec} from manifest`); + } + } + let toolPath = this.findVersionInHostedToolCacheDirectory(); + if (toolPath) { + core.info(`Found in cache @ ${toolPath}`); + } + else { + let downloadPath = ''; + try { + core.info(`Attempting to download ${this.nodeInfo.versionSpec}...`); + const versionInfo = yield this.getInfoFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest); + if (versionInfo) { + core.info(`Acquiring ${versionInfo.resolvedVersion} - ${versionInfo.arch} from ${versionInfo.downloadUrl}`); + downloadPath = yield tc.downloadTool(versionInfo.downloadUrl, undefined, this.nodeInfo.auth); + if (downloadPath) { + toolPath = yield this.extractArchive(downloadPath, versionInfo); + } + } + else { + core.info('Not found in manifest. Falling back to download directly from Node'); + } + } + catch (err) { + // Rate limit? + if (err instanceof tc.HTTPError && + (err.httpStatusCode === 403 || err.httpStatusCode === 429)) { + core.info(`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`); + } + else { + core.info(err.message); + } + core.debug(err.stack); + core.info('Falling back to download directly from Node'); + } + if (!toolPath) { + const nodeJsVersions = yield this.getNodeJsVersions(); + const versions = this.filterVersions(nodeJsVersions); + const evaluatedVersion = this.evaluateVersions(versions); + if (!evaluatedVersion) { + throw new Error(`Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`); + } + const toolName = this.getNodejsDistInfo(evaluatedVersion); + toolPath = yield this.downloadNodejs(toolName); + } + } + if (this.osPlat != 'win32') { + toolPath = path_1.default.join(toolPath, 'bin'); + } + core.addPath(toolPath); + }); + } + evaluateVersions(versions) { + let version = ''; + if (this.isLatestSyntax(this.nodeInfo.versionSpec)) { + core.info(`getting latest node version...`); + return versions[0]; + } + version = super.evaluateVersions(versions); + return version; + } + getDistributionUrl() { + return `https://nodejs.org/dist`; + } + getManifest() { + core.debug('Getting manifest from actions/node-versions@main'); + return tc.getManifestFromRepo('actions', 'node-versions', this.nodeInfo.auth, 'main'); + } + resolveLtsAliasFromManifest(versionSpec, stable, manifest) { + var _a; + const alias = (_a = versionSpec.split('lts/')[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + if (!alias) { + throw new Error(`Unable to parse LTS alias for Node version '${versionSpec}'`); + } + core.debug(`LTS alias '${alias}' for Node version '${versionSpec}'`); + // Supported formats are `lts/`, `lts/*`, and `lts/-n`. Where asterisk means highest possible LTS and -n means the nth-highest. + const n = Number(alias); + const aliases = Object.fromEntries(manifest + .filter(x => x.lts && x.stable === stable) + .map(x => [x.lts.toLowerCase(), x]) + .reverse()); + const numbered = Object.values(aliases); + const release = alias === '*' + ? numbered[numbered.length - 1] + : n < 0 + ? numbered[numbered.length - 1 + n] + : aliases[alias]; + if (!release) { + throw new Error(`Unable to find LTS release '${alias}' for Node version '${versionSpec}'.`); + } + core.debug(`Found LTS release '${release.version}' for Node version '${versionSpec}'`); + return release.version.split('.')[0]; + } + resolveVersionFromManifest(versionSpec, stable, osArch, manifest) { + return __awaiter(this, void 0, void 0, function* () { + try { + const info = yield this.getInfoFromManifest(versionSpec, stable, osArch, manifest); + return info === null || info === void 0 ? void 0 : info.resolvedVersion; + } + catch (err) { + core.info('Unable to resolve version from manifest...'); + core.debug(err.message); + } + }); + } + getInfoFromManifest(versionSpec, stable, osArch, manifest) { + return __awaiter(this, void 0, void 0, function* () { + let info = null; + if (!manifest) { + core.debug('No manifest cached'); + manifest = yield this.getManifest(); + } + const rel = yield tc.findFromManifest(versionSpec, stable, manifest, osArch); + if (rel && rel.files.length > 0) { + info = {}; + info.resolvedVersion = rel.version; + info.arch = rel.files[0].arch; + info.downloadUrl = rel.files[0].download_url; + info.fileName = rel.files[0].filename; + } + return info; + }); + } + isLtsAlias(versionSpec) { + return versionSpec.startsWith('lts/'); + } + isLatestSyntax(versionSpec) { + return ['current', 'latest', 'node'].includes(versionSpec); + } +} +exports["default"] = OfficialBuilds; /***/ }), @@ -71958,21 +71974,21 @@ exports["default"] = OfficialBuilds; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const base_distribution_1 = __importDefault(__nccwpck_require__(7)); -class RcBuild extends base_distribution_1.default { - constructor(nodeInfo) { - super(nodeInfo); - } - getDistributionUrl() { - return 'https://nodejs.org/download/rc'; - } -} -exports["default"] = RcBuild; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const base_distribution_1 = __importDefault(__nccwpck_require__(7)); +class RcBuild extends base_distribution_1.default { + constructor(nodeInfo) { + super(nodeInfo); + } + getDistributionUrl() { + return 'https://nodejs.org/download/rc'; + } +} +exports["default"] = RcBuild; /***/ }), @@ -71981,22 +71997,22 @@ exports["default"] = RcBuild; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const base_distribution_prerelease_1 = __importDefault(__nccwpck_require__(957)); -class CanaryBuild extends base_distribution_prerelease_1.default { - constructor(nodeInfo) { - super(nodeInfo); - this.distribution = 'v8-canary'; - } - getDistributionUrl() { - return 'https://nodejs.org/download/v8-canary'; - } -} -exports["default"] = CanaryBuild; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const base_distribution_prerelease_1 = __importDefault(__nccwpck_require__(957)); +class CanaryBuild extends base_distribution_prerelease_1.default { + constructor(nodeInfo) { + super(nodeInfo); + this.distribution = 'v8-canary'; + } + getDistributionUrl() { + return 'https://nodejs.org/download/v8-canary'; + } +} +exports["default"] = CanaryBuild; /***/ }), @@ -72005,122 +72021,122 @@ exports["default"] = CanaryBuild; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.run = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const os_1 = __importDefault(__nccwpck_require__(2037)); -const auth = __importStar(__nccwpck_require__(7573)); -const path = __importStar(__nccwpck_require__(1017)); -const cache_restore_1 = __nccwpck_require__(9517); -const cache_utils_1 = __nccwpck_require__(1678); -const installer_factory_1 = __nccwpck_require__(5617); -const util_1 = __nccwpck_require__(2629); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - // - // Version is optional. If supplied, install / use from the tool cache - // If not supplied then task is still used to setup proxy, auth, etc... - // - const version = resolveVersionInput(); - let arch = core.getInput('architecture'); - const cache = core.getInput('cache'); - // if architecture supplied but node-version is not - // if we don't throw a warning, the already installed x64 node will be used which is not probably what user meant. - if (arch && !version) { - core.warning('`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed. To fix this, provide `architecture` in combination with `node-version`'); - } - if (!arch) { - arch = os_1.default.arch(); - } - if (version) { - const token = core.getInput('token'); - const auth = !token ? undefined : `token ${token}`; - const stable = (core.getInput('stable') || 'true').toUpperCase() === 'TRUE'; - const checkLatest = (core.getInput('check-latest') || 'false').toUpperCase() === 'TRUE'; - const nodejsInfo = { - versionSpec: version, - checkLatest, - auth, - stable, - arch - }; - const nodeDistribution = installer_factory_1.getNodejsDistribution(nodejsInfo); - yield nodeDistribution.setupNodeJs(); - } - yield util_1.printEnvDetailsAndSetOutput(); - const registryUrl = core.getInput('registry-url'); - const alwaysAuth = core.getInput('always-auth'); - if (registryUrl) { - auth.configAuthentication(registryUrl, alwaysAuth); - } - if (cache && cache_utils_1.isCacheFeatureAvailable()) { - const cacheDependencyPath = core.getInput('cache-dependency-path'); - yield cache_restore_1.restoreCache(cache, cacheDependencyPath); - } - const matchersPath = path.join(__dirname, '../..', '.github'); - core.info(`##[add-matcher]${path.join(matchersPath, 'tsc.json')}`); - core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-stylish.json')}`); - core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-compact.json')}`); - } - catch (err) { - core.setFailed(err.message); - } - }); -} -exports.run = run; -function resolveVersionInput() { - let version = core.getInput('node-version'); - const versionFileInput = core.getInput('node-version-file'); - if (version && versionFileInput) { - core.warning('Both node-version and node-version-file inputs are specified, only node-version will be used'); - } - if (version) { - return version; - } - if (versionFileInput) { - const versionFilePath = path.join(process.env.GITHUB_WORKSPACE, versionFileInput); - if (!fs_1.default.existsSync(versionFilePath)) { - throw new Error(`The specified node version file at: ${versionFilePath} does not exist`); - } - version = util_1.parseNodeVersionFile(fs_1.default.readFileSync(versionFilePath, 'utf8')); - core.info(`Resolved ${versionFileInput} as ${version}`); - } - return version; -} + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.run = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const os_1 = __importDefault(__nccwpck_require__(2037)); +const auth = __importStar(__nccwpck_require__(7573)); +const path = __importStar(__nccwpck_require__(1017)); +const cache_restore_1 = __nccwpck_require__(9517); +const cache_utils_1 = __nccwpck_require__(1678); +const installer_factory_1 = __nccwpck_require__(5617); +const util_1 = __nccwpck_require__(2629); +function run() { + return __awaiter(this, void 0, void 0, function* () { + try { + // + // Version is optional. If supplied, install / use from the tool cache + // If not supplied then task is still used to setup proxy, auth, etc... + // + const version = resolveVersionInput(); + let arch = core.getInput('architecture'); + const cache = core.getInput('cache'); + // if architecture supplied but node-version is not + // if we don't throw a warning, the already installed x64 node will be used which is not probably what user meant. + if (arch && !version) { + core.warning('`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed. To fix this, provide `architecture` in combination with `node-version`'); + } + if (!arch) { + arch = os_1.default.arch(); + } + if (version) { + const token = core.getInput('token'); + const auth = !token ? undefined : `token ${token}`; + const stable = (core.getInput('stable') || 'true').toUpperCase() === 'TRUE'; + const checkLatest = (core.getInput('check-latest') || 'false').toUpperCase() === 'TRUE'; + const nodejsInfo = { + versionSpec: version, + checkLatest, + auth, + stable, + arch + }; + const nodeDistribution = installer_factory_1.getNodejsDistribution(nodejsInfo); + yield nodeDistribution.setupNodeJs(); + } + yield util_1.printEnvDetailsAndSetOutput(); + const registryUrl = core.getInput('registry-url'); + const alwaysAuth = core.getInput('always-auth'); + if (registryUrl) { + auth.configAuthentication(registryUrl, alwaysAuth); + } + if (cache && cache_utils_1.isCacheFeatureAvailable()) { + const cacheDependencyPath = core.getInput('cache-dependency-path'); + yield cache_restore_1.restoreCache(cache, cacheDependencyPath); + } + const matchersPath = path.join(__dirname, '../..', '.github'); + core.info(`##[add-matcher]${path.join(matchersPath, 'tsc.json')}`); + core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-stylish.json')}`); + core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-compact.json')}`); + } + catch (err) { + core.setFailed(err.message); + } + }); +} +exports.run = run; +function resolveVersionInput() { + let version = core.getInput('node-version'); + const versionFileInput = core.getInput('node-version-file'); + if (version && versionFileInput) { + core.warning('Both node-version and node-version-file inputs are specified, only node-version will be used'); + } + if (version) { + return version; + } + if (versionFileInput) { + const versionFilePath = path.join(process.env.GITHUB_WORKSPACE, versionFileInput); + if (!fs_1.default.existsSync(versionFilePath)) { + throw new Error(`The specified node version file at: ${versionFilePath} does not exist`); + } + version = util_1.parseNodeVersionFile(fs_1.default.readFileSync(versionFilePath, 'utf8')); + core.info(`Resolved ${versionFileInput} as ${version}`); + } + return version; +} /***/ }), @@ -72129,98 +72145,98 @@ function resolveVersionInput() { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.printEnvDetailsAndSetOutput = exports.parseNodeVersionFile = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const exec = __importStar(__nccwpck_require__(1514)); -function parseNodeVersionFile(contents) { - var _a, _b, _c; - let nodeVersion; - // Try parsing the file as an NPM `package.json` file. - try { - nodeVersion = (_a = JSON.parse(contents).volta) === null || _a === void 0 ? void 0 : _a.node; - if (!nodeVersion) - nodeVersion = (_b = JSON.parse(contents).engines) === null || _b === void 0 ? void 0 : _b.node; - } - catch (_d) { - core.info('Node version file is not JSON file'); - } - if (!nodeVersion) { - const found = contents.match(/^(?:nodejs\s+)?v?(?[^\s]+)$/m); - nodeVersion = (_c = found === null || found === void 0 ? void 0 : found.groups) === null || _c === void 0 ? void 0 : _c.version; - } - // In the case of an unknown format, - // return as is and evaluate the version separately. - if (!nodeVersion) - nodeVersion = contents.trim(); - return nodeVersion; -} -exports.parseNodeVersionFile = parseNodeVersionFile; -function printEnvDetailsAndSetOutput() { - return __awaiter(this, void 0, void 0, function* () { - core.startGroup('Environment details'); - const promises = ['node', 'npm', 'yarn'].map((tool) => __awaiter(this, void 0, void 0, function* () { - const output = yield getToolVersion(tool, ['--version']); - return { tool, output }; - })); - const tools = yield Promise.all(promises); - tools.forEach(({ tool, output }) => { - if (tool === 'node') { - core.setOutput(`${tool}-version`, output); - } - core.info(`${tool}: ${output}`); - }); - core.endGroup(); - }); -} -exports.printEnvDetailsAndSetOutput = printEnvDetailsAndSetOutput; -function getToolVersion(tool, options) { - return __awaiter(this, void 0, void 0, function* () { - try { - const { stdout, stderr, exitCode } = yield exec.getExecOutput(tool, options, { - ignoreReturnCode: true, - silent: true - }); - if (exitCode > 0) { - core.info(`[warning]${stderr}`); - return ''; - } - return stdout.trim(); - } - catch (err) { - return ''; - } - }); -} + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.printEnvDetailsAndSetOutput = exports.parseNodeVersionFile = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +function parseNodeVersionFile(contents) { + var _a, _b, _c; + let nodeVersion; + // Try parsing the file as an NPM `package.json` file. + try { + nodeVersion = (_a = JSON.parse(contents).volta) === null || _a === void 0 ? void 0 : _a.node; + if (!nodeVersion) + nodeVersion = (_b = JSON.parse(contents).engines) === null || _b === void 0 ? void 0 : _b.node; + } + catch (_d) { + core.info('Node version file is not JSON file'); + } + if (!nodeVersion) { + const found = contents.match(/^(?:nodejs\s+)?v?(?[^\s]+)$/m); + nodeVersion = (_c = found === null || found === void 0 ? void 0 : found.groups) === null || _c === void 0 ? void 0 : _c.version; + } + // In the case of an unknown format, + // return as is and evaluate the version separately. + if (!nodeVersion) + nodeVersion = contents.trim(); + return nodeVersion; +} +exports.parseNodeVersionFile = parseNodeVersionFile; +function printEnvDetailsAndSetOutput() { + return __awaiter(this, void 0, void 0, function* () { + core.startGroup('Environment details'); + const promises = ['node', 'npm', 'yarn'].map((tool) => __awaiter(this, void 0, void 0, function* () { + const output = yield getToolVersion(tool, ['--version']); + return { tool, output }; + })); + const tools = yield Promise.all(promises); + tools.forEach(({ tool, output }) => { + if (tool === 'node') { + core.setOutput(`${tool}-version`, output); + } + core.info(`${tool}: ${output}`); + }); + core.endGroup(); + }); +} +exports.printEnvDetailsAndSetOutput = printEnvDetailsAndSetOutput; +function getToolVersion(tool, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + const { stdout, stderr, exitCode } = yield exec.getExecOutput(tool, options, { + ignoreReturnCode: true, + silent: true + }); + if (exitCode > 0) { + core.info(`[warning]${stderr}`); + return ''; + } + return stdout.trim(); + } + catch (err) { + return ''; + } + }); +} /***/ }), @@ -72468,10 +72484,10 @@ var __webpack_exports__ = {}; (() => { "use strict"; var exports = __webpack_exports__; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const main_1 = __nccwpck_require__(399); -main_1.run(); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const main_1 = __nccwpck_require__(399); +main_1.run(); })(); diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 5df3e718a..c3e116ff8 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -1,6 +1,7 @@ import * as core from '@actions/core'; import * as exec from '@actions/exec'; import * as cache from '@actions/cache'; +import path from 'path'; type SupportedPackageManagers = { [prop: string]: PackageManagerInfo; @@ -30,11 +31,14 @@ export const supportedPackageManagers: SupportedPackageManagers = { } }; -export const getCommandOutput = async (toolCommand: string) => { +export const getCommandOutput = async ( + toolCommand: string, + cwd: string | null +) => { let {stdout, stderr, exitCode} = await exec.getExecOutput( toolCommand, undefined, - {ignoreReturnCode: true} + {ignoreReturnCode: true, ...(cwd !== null && {cwd})} ); if (exitCode) { @@ -47,11 +51,29 @@ export const getCommandOutput = async (toolCommand: string) => { return stdout.trim(); }; +const getPackageManagerWorkingDir = (): string | null => { + const projectDir = core.getInput('project-dir'); + if (projectDir) { + return projectDir; + } + + const cache = core.getInput('cache'); + if (cache !== 'yarn') { + return null; + } + + const cacheDependencyPath = core.getInput('cache-dependency-path'); + return cacheDependencyPath ? path.dirname(cacheDependencyPath) : null; +}; + const getPackageManagerVersion = async ( packageManager: string, command: string ) => { - const stdOut = await getCommandOutput(`${packageManager} ${command}`); + const stdOut = await getCommandOutput( + `${packageManager} ${command}`, + getPackageManagerWorkingDir() + ); if (!stdOut) { throw new Error(`Could not retrieve version of ${packageManager}`); @@ -85,7 +107,8 @@ export const getCacheDirectoryPath = async ( packageManager: string ) => { const stdOut = await getCommandOutput( - packageManagerInfo.getCacheFolderCommand + packageManagerInfo.getCacheFolderCommand, + getPackageManagerWorkingDir() ); if (!stdOut) { From 2d87f2fcc7e45aca8f85bc25cca9420164e747b5 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Tue, 11 Apr 2023 08:38:20 +0200 Subject: [PATCH 02/21] Fix find lock file --- dist/cache-save/index.js | 7 ++++--- dist/setup/index.js | 9 +++++---- src/cache-restore.ts | 4 +++- src/cache-utils.ts | 2 +- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 996806004..5107d00b5 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -59248,7 +59248,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -59294,8 +59294,9 @@ const getPackageManagerWorkingDir = () => { const cacheDependencyPath = core.getInput('cache-dependency-path'); return cacheDependencyPath ? path_1.default.dirname(cacheDependencyPath) : null; }; +exports.getPackageManagerWorkingDir = getPackageManagerWorkingDir; const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`, getPackageManagerWorkingDir()); + const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`, exports.getPackageManagerWorkingDir()); if (!stdOut) { throw new Error(`Could not retrieve version of ${packageManager}`); } @@ -59324,7 +59325,7 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void }); exports.getPackageManagerInfo = getPackageManagerInfo; const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand, getPackageManagerWorkingDir()); + const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand, exports.getPackageManagerWorkingDir()); if (!stdOut) { throw new Error(`Could not get cache folder path for ${packageManager}`); } diff --git a/dist/setup/index.js b/dist/setup/index.js index 6bc89acf4..e7f716781 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71167,7 +71167,7 @@ const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, exports.restoreCache = restoreCache; const findLockFile = (packageManager) => { const lockFiles = packageManager.lockFilePatterns; - const workspace = process.env.GITHUB_WORKSPACE; + const workspace = cache_utils_1.getPackageManagerWorkingDir() || process.env.GITHUB_WORKSPACE; const rootContent = fs_1.default.readdirSync(workspace); const lockFile = lockFiles.find(item => rootContent.includes(item)); if (!lockFile) { @@ -71216,7 +71216,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -71262,8 +71262,9 @@ const getPackageManagerWorkingDir = () => { const cacheDependencyPath = core.getInput('cache-dependency-path'); return cacheDependencyPath ? path_1.default.dirname(cacheDependencyPath) : null; }; +exports.getPackageManagerWorkingDir = getPackageManagerWorkingDir; const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`, getPackageManagerWorkingDir()); + const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`, exports.getPackageManagerWorkingDir()); if (!stdOut) { throw new Error(`Could not retrieve version of ${packageManager}`); } @@ -71292,7 +71293,7 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void }); exports.getPackageManagerInfo = getPackageManagerInfo; const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand, getPackageManagerWorkingDir()); + const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand, exports.getPackageManagerWorkingDir()); if (!stdOut) { throw new Error(`Could not get cache folder path for ${packageManager}`); } diff --git a/src/cache-restore.ts b/src/cache-restore.ts index c6f14ad7a..733e486a8 100644 --- a/src/cache-restore.ts +++ b/src/cache-restore.ts @@ -8,6 +8,7 @@ import {State} from './constants'; import { getCacheDirectoryPath, getPackageManagerInfo, + getPackageManagerWorkingDir, PackageManagerInfo } from './cache-utils'; @@ -55,7 +56,8 @@ export const restoreCache = async ( const findLockFile = (packageManager: PackageManagerInfo) => { const lockFiles = packageManager.lockFilePatterns; - const workspace = process.env.GITHUB_WORKSPACE!; + const workspace = + getPackageManagerWorkingDir() || process.env.GITHUB_WORKSPACE!; const rootContent = fs.readdirSync(workspace); const lockFile = lockFiles.find(item => rootContent.includes(item)); diff --git a/src/cache-utils.ts b/src/cache-utils.ts index c3e116ff8..5d54cee6e 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -51,7 +51,7 @@ export const getCommandOutput = async ( return stdout.trim(); }; -const getPackageManagerWorkingDir = (): string | null => { +export const getPackageManagerWorkingDir = (): string | null => { const projectDir = core.getInput('project-dir'); if (projectDir) { return projectDir; From 0b6156785a397353515da665c0ebb34dc77c5194 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Thu, 13 Apr 2023 09:19:36 +0200 Subject: [PATCH 03/21] Remove package-dir input --- action.yml | 2 -- src/cache-utils.ts | 4 ---- 2 files changed, 6 deletions(-) diff --git a/action.yml b/action.yml index 9e73a2954..56025a40a 100644 --- a/action.yml +++ b/action.yml @@ -25,8 +25,6 @@ inputs: description: 'Used to specify a package manager for caching in the default directory. Supported values: npm, yarn, pnpm.' cache-dependency-path: description: 'Used to specify the path to a dependency file: package-lock.json, yarn.lock, etc. Supports wildcards or a list of file names for caching multiple dependencies.' - project-dir: - description: 'Optional path used as a current working directory during executing package manager commands. Important if project directory is not the same as root.' # TODO: add input to control forcing to pull from cloud or dist. # escape valve for someone having issues or needing the absolute latest which isn't cached yet outputs: diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 5d54cee6e..38ea11e5f 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -52,10 +52,6 @@ export const getCommandOutput = async ( }; export const getPackageManagerWorkingDir = (): string | null => { - const projectDir = core.getInput('project-dir'); - if (projectDir) { - return projectDir; - } const cache = core.getInput('cache'); if (cache !== 'yarn') { From 9e025d3ea130c48565213325507357643c39a742 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Thu, 13 Apr 2023 12:30:59 +0200 Subject: [PATCH 04/21] format & resolve conflicts --- dist/cache-save/index.js | 4 ---- dist/setup/index.js | 4 ---- src/cache-utils.ts | 1 - 3 files changed, 9 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 5107d00b5..fc0242b12 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -59283,10 +59283,6 @@ const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, }); exports.getCommandOutput = getCommandOutput; const getPackageManagerWorkingDir = () => { - const projectDir = core.getInput('project-dir'); - if (projectDir) { - return projectDir; - } const cache = core.getInput('cache'); if (cache !== 'yarn') { return null; diff --git a/dist/setup/index.js b/dist/setup/index.js index e7f716781..38be17308 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71251,10 +71251,6 @@ const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, }); exports.getCommandOutput = getCommandOutput; const getPackageManagerWorkingDir = () => { - const projectDir = core.getInput('project-dir'); - if (projectDir) { - return projectDir; - } const cache = core.getInput('cache'); if (cache !== 'yarn') { return null; diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 38ea11e5f..afc19d65b 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -52,7 +52,6 @@ export const getCommandOutput = async ( }; export const getPackageManagerWorkingDir = (): string | null => { - const cache = core.getInput('cache'); if (cache !== 'yarn') { return null; From 9b43de6ca31a6d5489b999f43686e5e5bc44bd47 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Wed, 19 Apr 2023 16:15:09 +0200 Subject: [PATCH 05/21] Add unit tests --- __tests__/authutil.test.ts | 64 ++++++++++++++++++++++++++++++++++++++ dist/cache-save/index.js | 5 +-- dist/setup/index.js | 5 +-- src/cache-utils.ts | 2 +- 4 files changed, 71 insertions(+), 5 deletions(-) diff --git a/__tests__/authutil.test.ts b/__tests__/authutil.test.ts index 104680808..cc1c74788 100644 --- a/__tests__/authutil.test.ts +++ b/__tests__/authutil.test.ts @@ -4,6 +4,8 @@ import * as path from 'path'; import * as core from '@actions/core'; import * as io from '@actions/io'; import * as auth from '../src/authutil'; +import * as cacheUtils from '../src/cache-utils'; +import {getCacheDirectoryPath} from '../src/cache-utils'; let rcFile: string; @@ -209,4 +211,66 @@ describe('authutil tests', () => { `@otherscope:registry=MMM${os.EOL}//registry.npmjs.org/:_authToken=\${NODE_AUTH_TOKEN}${os.EOL}@myscope:registry=https://registry.npmjs.org/${os.EOL}always-auth=true` ); }); + + it('getPackageManagerWorkingDir should return null for not yarn', async () => { + process.env['INPUT_CACHE'] = 'some'; + delete process.env['INPUT_CACHE-DEPENDENCY-PATH']; + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toBeNull(); + }); + + it('getPackageManagerWorkingDir should return null for not yarn with cache-dependency-path', async () => { + process.env['INPUT_CACHE'] = 'some'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = '/foo/bar'; + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toBeNull(); + }); + + it('getPackageManagerWorkingDir should return null for yarn but without cache-dependency-path', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + delete process.env['INPUT_CACHE-DEPENDENCY-PATH']; + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toBeNull(); + }); + + it('getPackageManagerWorkingDir should return path for yarn with cache-dependency-path', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + const cachePath = '/foo/bar'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toEqual(path.dirname(cachePath)); + }); + + it('getCommandOutput(getPackageManagerVersion) should be called from with getPackageManagerWorkingDir result', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + const cachePath = '/foo/bar'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; + const getCommandOutputSpy = jest + .spyOn(cacheUtils, 'getCommandOutput') + .mockReturnValue(Promise.resolve('baz')); + + const version = await cacheUtils.getPackageManagerVersion('foo', 'bar'); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + `foo bar`, + path.dirname(cachePath) + ); + }); + + it('getCommandOutput(getCacheDirectoryPath) should be called from with getPackageManagerWorkingDir result', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + const cachePath = '/foo/bar'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; + const getCommandOutputSpy = jest + .spyOn(cacheUtils, 'getCommandOutput') + .mockReturnValue(Promise.resolve('baz')); + + const version = await cacheUtils.getCacheDirectoryPath( + {lockFilePatterns: [], getCacheFolderCommand: 'quz'}, + '' + ); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + `quz`, + path.dirname(cachePath) + ); + }); }); diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index fc0242b12..2fd095466 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -59248,7 +59248,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerVersion = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -59298,6 +59298,7 @@ const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, } return stdOut; }); +exports.getPackageManagerVersion = getPackageManagerVersion; const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { if (packageManager === 'npm') { return exports.supportedPackageManagers.npm; @@ -59306,7 +59307,7 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void return exports.supportedPackageManagers.pnpm; } else if (packageManager === 'yarn') { - const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); + const yarnVersion = yield exports.getPackageManagerVersion('yarn', '--version'); core.debug(`Consumed yarn version is ${yarnVersion}`); if (yarnVersion.startsWith('1.')) { return exports.supportedPackageManagers.yarn1; diff --git a/dist/setup/index.js b/dist/setup/index.js index 38be17308..c86bcfb5d 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71216,7 +71216,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerVersion = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -71266,6 +71266,7 @@ const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, } return stdOut; }); +exports.getPackageManagerVersion = getPackageManagerVersion; const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { if (packageManager === 'npm') { return exports.supportedPackageManagers.npm; @@ -71274,7 +71275,7 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void return exports.supportedPackageManagers.pnpm; } else if (packageManager === 'yarn') { - const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); + const yarnVersion = yield exports.getPackageManagerVersion('yarn', '--version'); core.debug(`Consumed yarn version is ${yarnVersion}`); if (yarnVersion.startsWith('1.')) { return exports.supportedPackageManagers.yarn1; diff --git a/src/cache-utils.ts b/src/cache-utils.ts index afc19d65b..804768a64 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -61,7 +61,7 @@ export const getPackageManagerWorkingDir = (): string | null => { return cacheDependencyPath ? path.dirname(cacheDependencyPath) : null; }; -const getPackageManagerVersion = async ( +export const getPackageManagerVersion = async ( packageManager: string, command: string ) => { From 02b94f2c876854bee5c78da9cc36f24dd06c1d6f Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Mon, 24 Apr 2023 09:28:37 +0200 Subject: [PATCH 06/21] build dist --- dist/cache-save/index.js | 3398 +++++++++++++++++++++----------------- dist/setup/index.js | 3398 +++++++++++++++++++++----------------- 2 files changed, 3778 insertions(+), 3018 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 2fd095466..c974b0872 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -6980,19 +6980,18 @@ function copyFile(srcFile, destFile, force) { /***/ }), /***/ 2557: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib = __nccwpck_require__(9268); - // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var listenersMap = new WeakMap(); -var abortedMap = new WeakMap(); +/// +const listenersMap = new WeakMap(); +const abortedMap = new WeakMap(); /** * An aborter instance implements AbortSignal interface, can abort HTTP requests. * @@ -7006,8 +7005,8 @@ var abortedMap = new WeakMap(); * await doAsyncWork(AbortSignal.none); * ``` */ -var AbortSignal = /** @class */ (function () { - function AbortSignal() { +class AbortSignal { + constructor() { /** * onabort event listener. */ @@ -7015,74 +7014,65 @@ var AbortSignal = /** @class */ (function () { listenersMap.set(this, []); abortedMap.set(this, false); } - Object.defineProperty(AbortSignal.prototype, "aborted", { - /** - * Status of whether aborted or not. - * - * @readonly - */ - get: function () { - if (!abortedMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - return abortedMap.get(this); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AbortSignal, "none", { - /** - * Creates a new AbortSignal instance that will never be aborted. - * - * @readonly - */ - get: function () { - return new AbortSignal(); - }, - enumerable: false, - configurable: true - }); + /** + * Status of whether aborted or not. + * + * @readonly + */ + get aborted() { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + return abortedMap.get(this); + } + /** + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + */ + static get none() { + return new AbortSignal(); + } /** * Added new "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be added */ - AbortSignal.prototype.addEventListener = function ( + addEventListener( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - var listeners = listenersMap.get(this); + const listeners = listenersMap.get(this); listeners.push(listener); - }; + } /** * Remove "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be removed */ - AbortSignal.prototype.removeEventListener = function ( + removeEventListener( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - var listeners = listenersMap.get(this); - var index = listeners.indexOf(listener); + const listeners = listenersMap.get(this); + const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } - }; + } /** * Dispatches a synthetic event to the AbortSignal. */ - AbortSignal.prototype.dispatchEvent = function (_event) { + dispatchEvent(_event) { throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); - }; - return AbortSignal; -}()); + } +} /** * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. * Will try to trigger abort event for all linked AbortSignal nodes. @@ -7100,12 +7090,12 @@ function abortSignal(signal) { if (signal.onabort) { signal.onabort.call(signal); } - var listeners = listenersMap.get(signal); + const listeners = listenersMap.get(signal); if (listeners) { // Create a copy of listeners so mutations to the array // (e.g. via removeListener calls) don't affect the listeners // we invoke. - listeners.slice().forEach(function (listener) { + listeners.slice().forEach((listener) => { listener.call(signal, { type: "abort" }); }); } @@ -7131,15 +7121,12 @@ function abortSignal(signal) { * } * ``` */ -var AbortError = /** @class */ (function (_super) { - tslib.__extends(AbortError, _super); - function AbortError(message) { - var _this = _super.call(this, message) || this; - _this.name = "AbortError"; - return _this; +class AbortError extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } - return AbortError; -}(Error)); +} /** * An AbortController provides an AbortSignal and the associated controls to signal * that an asynchronous operation should be aborted. @@ -7174,10 +7161,9 @@ var AbortError = /** @class */ (function (_super) { * await doAsyncWork(aborter.withTimeout(25 * 1000)); * ``` */ -var AbortController = /** @class */ (function () { +class AbortController { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - function AbortController(parentSignals) { - var _this = this; + constructor(parentSignals) { this._signal = new AbortSignal(); if (!parentSignals) { return; @@ -7187,8 +7173,7 @@ var AbortController = /** @class */ (function () { // eslint-disable-next-line prefer-rest-params parentSignals = arguments; } - for (var _i = 0, parentSignals_1 = parentSignals; _i < parentSignals_1.length; _i++) { - var parentSignal = parentSignals_1[_i]; + for (const parentSignal of parentSignals) { // if the parent signal has already had abort() called, // then call abort on this signal as well. if (parentSignal.aborted) { @@ -7196,47 +7181,42 @@ var AbortController = /** @class */ (function () { } else { // when the parent signal aborts, this signal should as well. - parentSignal.addEventListener("abort", function () { - _this.abort(); + parentSignal.addEventListener("abort", () => { + this.abort(); }); } } } - Object.defineProperty(AbortController.prototype, "signal", { - /** - * The AbortSignal associated with this controller that will signal aborted - * when the abort method is called on this controller. - * - * @readonly - */ - get: function () { - return this._signal; - }, - enumerable: false, - configurable: true - }); + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + get signal() { + return this._signal; + } /** * Signal that any operations passed this controller's associated abort signal * to cancel any remaining work and throw an `AbortError`. */ - AbortController.prototype.abort = function () { + abort() { abortSignal(this._signal); - }; + } /** * Creates a new AbortSignal instance that will abort after the provided ms. * @param ms - Elapsed time in milliseconds to trigger an abort. */ - AbortController.timeout = function (ms) { - var signal = new AbortSignal(); - var timer = setTimeout(abortSignal, ms, signal); + static timeout(ms) { + const signal = new AbortSignal(); + const timer = setTimeout(abortSignal, ms, signal); // Prevent the active Timer from keeping the Node.js event loop active. if (typeof timer.unref === "function") { timer.unref(); } return signal; - }; - return AbortController; -}()); + } +} exports.AbortController = AbortController; exports.AbortError = AbortError; @@ -7244,333 +7224,6 @@ exports.AbortSignal = AbortSignal; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 9268: -/***/ ((module) => { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), - -/***/ 2356: -/***/ (() => { - -"use strict"; - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -if (typeof Symbol === undefined || !Symbol.asyncIterator) { - Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); -} -//# sourceMappingURL=index.js.map - /***/ }), /***/ 9645: @@ -14833,6 +14486,689 @@ exports["default"] = _default; Object.defineProperty(exports, "__esModule", ({ value: true })); var logger$1 = __nccwpck_require__(3233); +var abortController = __nccwpck_require__(2557); +var coreUtil = __nccwpck_require__(1333); + +// Copyright (c) Microsoft Corporation. +/** + * The `@azure/logger` configuration for this package. + * @internal + */ +const logger = logger$1.createClientLogger("core-lro"); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The default time interval to wait before sending the next polling request. + */ +const POLL_INTERVAL_IN_MS = 2000; +/** + * The closed set of terminal states. + */ +const terminalStates = ["succeeded", "canceled", "failed"]; + +// Copyright (c) Microsoft Corporation. +/** + * Deserializes the state + */ +function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; + } + catch (e) { + throw new Error(`Unable to deserialize input state: ${serializedState}`); + } +} +function setStateError(inputs) { + const { state, stateProxy, isOperationError } = inputs; + return (error) => { + if (isOperationError(error)) { + stateProxy.setError(state, error); + stateProxy.setFailed(state); + } + throw error; + }; +} +function processOperationStatus(result) { + const { state, stateProxy, status, isDone, processResult, response, setErrorAsResult } = result; + switch (status) { + case "succeeded": { + stateProxy.setSucceeded(state); + break; + } + case "failed": { + stateProxy.setError(state, new Error(`The long-running operation has failed`)); + stateProxy.setFailed(state); + break; + } + case "canceled": { + stateProxy.setCanceled(state); + break; + } + } + if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || + (isDone === undefined && + ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) { + stateProxy.setResult(state, buildResult({ + response, + state, + processResult, + })); + } +} +function buildResult(inputs) { + const { processResult, response, state } = inputs; + return processResult ? processResult(response, state) : response; +} +/** + * Initiates the long-running operation. + */ +async function initOperation(inputs) { + const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs; + const { operationLocation, resourceLocation, metadata, response } = await init(); + if (operationLocation) + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); + const config = { + metadata, + operationLocation, + resourceLocation, + }; + logger.verbose(`LRO: Operation description:`, config); + const state = stateProxy.initState(config); + const status = getOperationStatus({ response, state, operationLocation }); + processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult }); + return state; +} +async function pollOperationHelper(inputs) { + const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs; + const response = await poll(operationLocation, options).catch(setStateError({ + state, + stateProxy, + isOperationError, + })); + const status = getOperationStatus(response, state); + logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); + if (status === "succeeded") { + const resourceLocation = getResourceLocation(response, state); + if (resourceLocation !== undefined) { + return { + response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })), + status, + }; + } + } + return { response, status }; +} +/** Polls the long-running operation. */ +async function pollOperation(inputs) { + const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, updateState, setDelay, isDone, setErrorAsResult, } = inputs; + const { operationLocation } = state.config; + if (operationLocation !== undefined) { + const { response, status } = await pollOperationHelper({ + poll, + getOperationStatus, + state, + stateProxy, + operationLocation, + getResourceLocation, + isOperationError, + options, + }); + processOperationStatus({ + status, + response, + state, + stateProxy, + isDone, + processResult, + setErrorAsResult, + }); + if (!terminalStates.includes(status)) { + const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); + if (intervalInMs) + setDelay(intervalInMs); + const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state); + if (location !== undefined) { + const isUpdated = operationLocation !== location; + state.config.operationLocation = location; + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated); + } + else + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); + } + updateState === null || updateState === void 0 ? void 0 : updateState(state, response); + } +} + +// Copyright (c) Microsoft Corporation. +function getOperationLocationPollingUrl(inputs) { + const { azureAsyncOperation, operationLocation } = inputs; + return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; +} +function getLocationHeader(rawResponse) { + return rawResponse.headers["location"]; +} +function getOperationLocationHeader(rawResponse) { + return rawResponse.headers["operation-location"]; +} +function getAzureAsyncOperationHeader(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; +} +function findResourceLocation(inputs) { + const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; + switch (requestMethod) { + case "PUT": { + return requestPath; + } + case "DELETE": { + return undefined; + } + default: { + switch (resourceLocationConfig) { + case "azure-async-operation": { + return undefined; + } + case "original-uri": { + return requestPath; + } + case "location": + default: { + return location; + } + } + } + } +} +function inferLroMode(inputs) { + const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs; + const operationLocation = getOperationLocationHeader(rawResponse); + const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse); + const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation }); + const location = getLocationHeader(rawResponse); + const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase(); + if (pollingUrl !== undefined) { + return { + mode: "OperationLocation", + operationLocation: pollingUrl, + resourceLocation: findResourceLocation({ + requestMethod: normalizedRequestMethod, + location, + requestPath, + resourceLocationConfig, + }), + }; + } + else if (location !== undefined) { + return { + mode: "ResourceLocation", + operationLocation: location, + }; + } + else if (normalizedRequestMethod === "PUT" && requestPath) { + return { + mode: "Body", + operationLocation: requestPath, + }; + } + else { + return undefined; + } +} +function transformStatus(inputs) { + const { status, statusCode } = inputs; + if (typeof status !== "string" && status !== undefined) { + throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`); + } + switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) { + case undefined: + return toOperationStatus(statusCode); + case "succeeded": + return "succeeded"; + case "failed": + return "failed"; + case "running": + case "accepted": + case "started": + case "canceling": + case "cancelling": + return "running"; + case "canceled": + case "cancelled": + return "canceled"; + default: { + logger.verbose(`LRO: unrecognized operation status: ${status}`); + return status; + } + } +} +function getStatus(rawResponse) { + var _a; + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + return transformStatus({ status, statusCode: rawResponse.statusCode }); +} +function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return transformStatus({ status, statusCode: rawResponse.statusCode }); +} +function toOperationStatus(statusCode) { + if (statusCode === 202) { + return "running"; + } + else if (statusCode < 300) { + return "succeeded"; + } + else { + return "failed"; + } +} +function parseRetryAfter({ rawResponse }) { + const retryAfter = rawResponse.headers["retry-after"]; + if (retryAfter !== undefined) { + // Retry-After header value is either in HTTP date format, or in seconds + const retryAfterInSeconds = parseInt(retryAfter); + return isNaN(retryAfterInSeconds) + ? calculatePollingIntervalFromDate(new Date(retryAfter)) + : retryAfterInSeconds * 1000; + } + return undefined; +} +function calculatePollingIntervalFromDate(retryAfterDate) { + const timeNow = Math.floor(new Date().getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return undefined; +} +function getStatusFromInitialResponse(inputs) { + const { response, state, operationLocation } = inputs; + function helper() { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case undefined: + return toOperationStatus(response.rawResponse.statusCode); + case "Body": + return getOperationStatus(response, state); + default: + return "running"; + } + } + const status = helper(); + return status === "running" && operationLocation === undefined ? "succeeded" : status; +} +/** + * Initiates the long-running operation. + */ +async function initHttpOperation(inputs) { + const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs; + return initOperation({ + init: async () => { + const response = await lro.sendInitialRequest(); + const config = inferLroMode({ + rawResponse: response.rawResponse, + requestPath: lro.requestPath, + requestMethod: lro.requestMethod, + resourceLocationConfig, + }); + return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); + }, + stateProxy, + processResult: processResult + ? ({ flatResponse }, state) => processResult(flatResponse, state) + : ({ flatResponse }) => flatResponse, + getOperationStatus: getStatusFromInitialResponse, + setErrorAsResult, + }); +} +function getOperationLocation({ rawResponse }, state) { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case "OperationLocation": { + return getOperationLocationPollingUrl({ + operationLocation: getOperationLocationHeader(rawResponse), + azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse), + }); + } + case "ResourceLocation": { + return getLocationHeader(rawResponse); + } + case "Body": + default: { + return undefined; + } + } +} +function getOperationStatus({ rawResponse }, state) { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case "OperationLocation": { + return getStatus(rawResponse); + } + case "ResourceLocation": { + return toOperationStatus(rawResponse.statusCode); + } + case "Body": { + return getProvisioningState(rawResponse); + } + default: + throw new Error(`Internal error: Unexpected operation mode: ${mode}`); + } +} +function getResourceLocation({ flatResponse }, state) { + if (typeof flatResponse === "object") { + const resourceLocation = flatResponse.resourceLocation; + if (resourceLocation !== undefined) { + state.config.resourceLocation = resourceLocation; + } + } + return state.config.resourceLocation; +} +function isOperationError(e) { + return e.name === "RestError"; +} +/** Polls the long-running operation. */ +async function pollHttpOperation(inputs) { + const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs; + return pollOperation({ + state, + stateProxy, + setDelay, + processResult: processResult + ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState) + : ({ flatResponse }) => flatResponse, + updateState, + getPollingInterval: parseRetryAfter, + getOperationLocation, + getOperationStatus, + isOperationError, + getResourceLocation, + options, + /** + * The expansion here is intentional because `lro` could be an object that + * references an inner this, so we need to preserve a reference to it. + */ + poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions), + setErrorAsResult, + }); +} + +// Copyright (c) Microsoft Corporation. +const createStateProxy$1 = () => ({ + /** + * The state at this point is created to be of type OperationState. + * It will be updated later to be of type TState when the + * customer-provided callback, `updateState`, is called during polling. + */ + initState: (config) => ({ status: "running", config }), + setCanceled: (state) => (state.status = "canceled"), + setError: (state, error) => (state.error = error), + setResult: (state, result) => (state.result = result), + setRunning: (state) => (state.status = "running"), + setSucceeded: (state) => (state.status = "succeeded"), + setFailed: (state) => (state.status = "failed"), + getError: (state) => state.error, + getResult: (state) => state.result, + isCanceled: (state) => state.status === "canceled", + isFailed: (state) => state.status === "failed", + isRunning: (state) => state.status === "running", + isSucceeded: (state) => state.status === "succeeded", +}); +/** + * Returns a poller factory. + */ +function buildCreatePoller(inputs) { + const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, resolveOnUnsuccessful, } = inputs; + return async ({ init, poll }, options) => { + const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {}; + const stateProxy = createStateProxy$1(); + const withOperationLocation = withOperationLocationCallback + ? (() => { + let called = false; + return (operationLocation, isUpdated) => { + if (isUpdated) + withOperationLocationCallback(operationLocation); + else if (!called) + withOperationLocationCallback(operationLocation); + called = true; + }; + })() + : undefined; + const state = restoreFrom + ? deserializeState(restoreFrom) + : await initOperation({ + init, + stateProxy, + processResult, + getOperationStatus: getStatusFromInitialResponse, + withOperationLocation, + setErrorAsResult: !resolveOnUnsuccessful, + }); + let resultPromise; + const abortController$1 = new abortController.AbortController(); + const handlers = new Map(); + const handleProgressEvents = async () => handlers.forEach((h) => h(state)); + const cancelErrMsg = "Operation was canceled"; + let currentPollIntervalInMs = intervalInMs; + const poller = { + getOperationState: () => state, + getResult: () => state.result, + isDone: () => ["succeeded", "failed", "canceled"].includes(state.status), + isStopped: () => resultPromise === undefined, + stopPolling: () => { + abortController$1.abort(); + }, + toString: () => JSON.stringify({ + state, + }), + onProgress: (callback) => { + const s = Symbol(); + handlers.set(s, callback); + return () => handlers.delete(s); + }, + pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => { + const { abortSignal: inputAbortSignal } = pollOptions || {}; + const { signal: abortSignal } = inputAbortSignal + ? new abortController.AbortController([inputAbortSignal, abortController$1.signal]) + : abortController$1; + if (!poller.isDone()) { + await poller.poll({ abortSignal }); + while (!poller.isDone()) { + await coreUtil.delay(currentPollIntervalInMs, { abortSignal }); + await poller.poll({ abortSignal }); + } + } + if (resolveOnUnsuccessful) { + return poller.getResult(); + } + else { + switch (state.status) { + case "succeeded": + return poller.getResult(); + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; + case "notStarted": + case "running": + throw new Error(`Polling completed without succeeding or failing`); + } + } + })().finally(() => { + resultPromise = undefined; + }))), + async poll(pollOptions) { + if (resolveOnUnsuccessful) { + if (poller.isDone()) + return; + } + else { + switch (state.status) { + case "succeeded": + return; + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; + } + } + await pollOperation({ + poll, + state, + stateProxy, + getOperationLocation, + isOperationError, + withOperationLocation, + getPollingInterval, + getOperationStatus: getStatusFromPollResponse, + getResourceLocation, + processResult, + updateState, + options: pollOptions, + setDelay: (pollIntervalInMs) => { + currentPollIntervalInMs = pollIntervalInMs; + }, + setErrorAsResult: !resolveOnUnsuccessful, + }); + await handleProgressEvents(); + if (!resolveOnUnsuccessful) { + switch (state.status) { + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; + } + } + }, + }; + return poller; + }; +} + +// Copyright (c) Microsoft Corporation. +/** + * Creates a poller that can be used to poll a long-running operation. + * @param lro - Description of the long-running operation + * @param options - options to configure the poller + * @returns an initialized poller + */ +async function createHttpPoller(lro, options) { + const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {}; + return buildCreatePoller({ + getStatusFromInitialResponse, + getStatusFromPollResponse: getOperationStatus, + isOperationError, + getOperationLocation, + getResourceLocation, + getPollingInterval: parseRetryAfter, + resolveOnUnsuccessful, + })({ + init: async () => { + const response = await lro.sendInitialRequest(); + const config = inferLroMode({ + rawResponse: response.rawResponse, + requestPath: lro.requestPath, + requestMethod: lro.requestMethod, + resourceLocationConfig, + }); + return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); + }, + poll: lro.sendPollRequest, + }, { + intervalInMs, + withOperationLocation, + restoreFrom, + updateState, + processResult: processResult + ? ({ flatResponse }, state) => processResult(flatResponse, state) + : ({ flatResponse }) => flatResponse, + }); +} + +// Copyright (c) Microsoft Corporation. +const createStateProxy = () => ({ + initState: (config) => ({ config, isStarted: true }), + setCanceled: (state) => (state.isCancelled = true), + setError: (state, error) => (state.error = error), + setResult: (state, result) => (state.result = result), + setRunning: (state) => (state.isStarted = true), + setSucceeded: (state) => (state.isCompleted = true), + setFailed: () => { + /** empty body */ + }, + getError: (state) => state.error, + getResult: (state) => state.result, + isCanceled: (state) => !!state.isCancelled, + isFailed: (state) => !!state.error, + isRunning: (state) => !!state.isStarted, + isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error), +}); +class GenericPollOperation { + constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.setErrorAsResult = setErrorAsResult; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + async update(options) { + var _a; + const stateProxy = createStateProxy(); + if (!this.state.isStarted) { + this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({ + lro: this.lro, + stateProxy, + resourceLocationConfig: this.lroResourceLocationConfig, + processResult: this.processResult, + setErrorAsResult: this.setErrorAsResult, + }))); + } + const updateState = this.updateState; + const isDone = this.isDone; + if (!this.state.isCompleted && this.state.error === undefined) { + await pollHttpOperation({ + lro: this.lro, + state: this.state, + stateProxy, + processResult: this.processResult, + updateState: updateState + ? (state, { rawResponse }) => updateState(state, rawResponse) + : undefined, + isDone: isDone + ? ({ flatResponse }, state) => isDone(flatResponse, state) + : undefined, + options, + setDelay: (intervalInMs) => { + this.pollerConfig.intervalInMs = intervalInMs; + }, + setErrorAsResult: this.setErrorAsResult, + }); + } + (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state); + return this; + } + async cancel() { + logger.error("`cancelOperation` is deprecated because it wasn't implemented"); + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state, + }); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -14848,8 +15184,8 @@ class PollerStoppedError extends Error { } } /** - * When a poller is cancelled through the `cancelOperation` method, - * the poller will be rejected with an instance of the PollerCancelledError. + * When the operation is cancelled, the poller will be rejected with an instance + * of the PollerCancelledError. */ class PollerCancelledError extends Error { constructor(message) { @@ -14987,6 +15323,8 @@ class Poller { * @param operation - Must contain the basic properties of `PollOperation`. */ constructor(operation) { + /** controls whether to throw an error if the operation failed or was canceled. */ + this.resolveOnUnsuccessful = false; this.stopped = true; this.pollProgressCallbacks = []; this.operation = operation; @@ -15005,12 +15343,12 @@ class Poller { * Starts a loop that will break only if the poller is done * or if the poller is stopped. */ - async startPolling() { + async startPolling(pollOptions = {}) { if (this.stopped) { this.stopped = false; } while (!this.isStopped() && !this.isDone()) { - await this.poll(); + await this.poll(pollOptions); await this.delay(); } } @@ -15023,29 +15361,13 @@ class Poller { * @param options - Optional properties passed to the operation's update method. */ async pollOnce(options = {}) { - try { - if (!this.isDone()) { - this.operation = await this.operation.update({ - abortSignal: options.abortSignal, - fireProgress: this.fireProgress.bind(this), - }); - if (this.isDone() && this.resolve) { - // If the poller has finished polling, this means we now have a result. - // However, it can be the case that TResult is instantiated to void, so - // we are not expecting a result anyway. To assert that we might not - // have a result eventually after finishing polling, we cast the result - // to TResult. - this.resolve(this.operation.state.result); - } - } - } - catch (e) { - this.operation.state.error = e; - if (this.reject) { - this.reject(e); - } - throw e; + if (!this.isDone()) { + this.operation = await this.operation.update({ + abortSignal: options.abortSignal, + fireProgress: this.fireProgress.bind(this), + }); } + this.processUpdatedState(); } /** * fireProgress calls the functions passed in via onProgress the method of the poller. @@ -15061,14 +15383,10 @@ class Poller { } } /** - * Invokes the underlying operation's cancel method, and rejects the - * pollUntilDone promise. + * Invokes the underlying operation's cancel method. */ async cancelOnce(options = {}) { this.operation = await this.operation.cancel(options); - if (this.reject) { - this.reject(new PollerCancelledError("Poller cancelled")); - } } /** * Returns a promise that will resolve once a single polling request finishes. @@ -15088,13 +15406,41 @@ class Poller { } return this.pollOncePromise; } + processUpdatedState() { + if (this.operation.state.error) { + this.stopped = true; + if (!this.resolveOnUnsuccessful) { + this.reject(this.operation.state.error); + throw this.operation.state.error; + } + } + if (this.operation.state.isCancelled) { + this.stopped = true; + if (!this.resolveOnUnsuccessful) { + const error = new PollerCancelledError("Operation was canceled"); + this.reject(error); + throw error; + } + } + if (this.isDone() && this.resolve) { + // If the poller has finished polling, this means we now have a result. + // However, it can be the case that TResult is instantiated to void, so + // we are not expecting a result anyway. To assert that we might not + // have a result eventually after finishing polling, we cast the result + // to TResult. + this.resolve(this.getResult()); + } + } /** * Returns a promise that will resolve once the underlying operation is completed. */ - async pollUntilDone() { + async pollUntilDone(pollOptions = {}) { if (this.stopped) { - this.startPolling().catch(this.reject); + this.startPolling(pollOptions).catch(this.reject); } + // This is needed because the state could have been updated by + // `cancelOperation`, e.g. the operation is canceled or an error occurred. + this.processUpdatedState(); return this.promise; } /** @@ -15143,9 +15489,6 @@ class Poller { * @param options - Optional properties passed to the operation's update method. */ cancelOperation(options = {}) { - if (!this.stopped) { - this.stopped = true; - } if (!this.cancelPromise) { this.cancelPromise = this.cancelOnce(options); } @@ -15225,344 +15568,18 @@ class Poller { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Detects where the continuation token is and returns it. Notice that azure-asyncoperation - * must be checked first before the other location headers because there are scenarios - * where both azure-asyncoperation and location could be present in the same response but - * azure-asyncoperation should be the one to use for polling. - */ -function getPollingUrl(rawResponse, defaultPath) { - var _a, _b, _c; - return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getOperationLocation(rawResponse)) !== null && _b !== void 0 ? _b : getLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath); -} -function getLocation(rawResponse) { - return rawResponse.headers["location"]; -} -function getOperationLocation(rawResponse) { - return rawResponse.headers["operation-location"]; -} -function getAzureAsyncOperation(rawResponse) { - return rawResponse.headers["azure-asyncoperation"]; -} -function findResourceLocation(requestMethod, rawResponse, requestPath) { - switch (requestMethod) { - case "PUT": { - return requestPath; - } - case "POST": - case "PATCH": { - return getLocation(rawResponse); - } - default: { - return undefined; - } - } -} -function inferLroMode(requestPath, requestMethod, rawResponse) { - if (getAzureAsyncOperation(rawResponse) !== undefined || - getOperationLocation(rawResponse) !== undefined) { - return { - mode: "Location", - resourceLocation: findResourceLocation(requestMethod, rawResponse, requestPath), - }; - } - else if (getLocation(rawResponse) !== undefined) { - return { - mode: "Location", - }; - } - else if (["PUT", "PATCH"].includes(requestMethod)) { - return { - mode: "Body", - }; - } - return {}; -} -class SimpleRestError extends Error { - constructor(message, statusCode) { - super(message); - this.name = "RestError"; - this.statusCode = statusCode; - Object.setPrototypeOf(this, SimpleRestError.prototype); - } -} -function isUnexpectedInitialResponse(rawResponse) { - const code = rawResponse.statusCode; - if (![203, 204, 202, 201, 200, 500].includes(code)) { - throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code); - } - return false; -} -function isUnexpectedPollingResponse(rawResponse) { - const code = rawResponse.statusCode; - if (![202, 201, 200, 500].includes(code)) { - throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); - } - return false; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -const successStates = ["succeeded"]; -const failureStates = ["failed", "canceled", "cancelled"]; - -// Copyright (c) Microsoft Corporation. -function getProvisioningState(rawResponse) { - var _a, _b; - const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; - return typeof state === "string" ? state.toLowerCase() : "succeeded"; -} -function isBodyPollingDone(rawResponse) { - const state = getProvisioningState(rawResponse); - if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { - throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); - } - return successStates.includes(state); -} -/** - * Creates a polling strategy based on BodyPolling which uses the provisioning state - * from the result to determine the current operation state - */ -function processBodyPollingOperationResult(response) { - return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) }); -} - -// Copyright (c) Microsoft Corporation. -/** - * The `@azure/logger` configuration for this package. - * @internal - */ -const logger = logger$1.createClientLogger("core-lro"); - -// Copyright (c) Microsoft Corporation. -function isPollingDone(rawResponse) { - var _a; - if (isUnexpectedPollingResponse(rawResponse) || rawResponse.statusCode === 202) { - return false; - } - const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const state = typeof status === "string" ? status.toLowerCase() : "succeeded"; - if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { - throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); - } - return successStates.includes(state); -} -/** - * Sends a request to the URI of the provisioned resource if needed. - */ -async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) { - switch (lroResourceLocationConfig) { - case "original-uri": - return lro.sendPollRequest(lro.requestPath); - case "azure-async-operation": - return undefined; - case "location": - default: - return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath); - } -} -function processLocationPollingOperationResult(lro, resourceLocation, lroResourceLocationConfig) { - return (response) => { - if (isPollingDone(response.rawResponse)) { - if (resourceLocation === undefined) { - return Object.assign(Object.assign({}, response), { done: true }); - } - else { - return Object.assign(Object.assign({}, response), { done: false, next: async () => { - const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig); - return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true }); - } }); - } - } - return Object.assign(Object.assign({}, response), { done: false }); - }; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -function processPassthroughOperationResult(response) { - return Object.assign(Object.assign({}, response), { done: true }); -} - -// Copyright (c) Microsoft Corporation. -/** - * creates a stepping function that maps an LRO state to another. - */ -function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) { - switch (config.mode) { - case "Location": { - return processLocationPollingOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig); - } - case "Body": { - return processBodyPollingOperationResult; - } - default: { - return processPassthroughOperationResult; - } - } -} -/** - * Creates a polling operation. - */ -function createPoll(lroPrimitives) { - return async (path, pollerConfig, getLroStatusFromResponse) => { - const response = await lroPrimitives.sendPollRequest(path); - const retryAfter = response.rawResponse.headers["retry-after"]; - if (retryAfter !== undefined) { - // Retry-After header value is either in HTTP date format, or in seconds - const retryAfterInSeconds = parseInt(retryAfter); - pollerConfig.intervalInMs = isNaN(retryAfterInSeconds) - ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) - : retryAfterInSeconds * 1000; - } - return getLroStatusFromResponse(response); - }; -} -function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { - const timeNow = Math.floor(new Date().getTime()); - const retryAfterTime = retryAfterDate.getTime(); - if (timeNow < retryAfterTime) { - return retryAfterTime - timeNow; - } - return defaultIntervalInMs; -} -/** - * Creates a callback to be used to initialize the polling operation state. - * @param state - of the polling operation - * @param operationSpec - of the LRO - * @param callback - callback to be called when the operation is done - * @returns callback that initializes the state of the polling operation - */ -function createInitializeState(state, requestPath, requestMethod) { - return (response) => { - if (isUnexpectedInitialResponse(response.rawResponse)) - ; - state.initialRawResponse = response.rawResponse; - state.isStarted = true; - state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath); - state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse); - /** short circuit polling if body polling is done in the initial request */ - if (state.config.mode === undefined || - (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) { - state.result = response.flatResponse; - state.isCompleted = true; - } - logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`); - return Boolean(state.isCompleted); - }; -} - -// Copyright (c) Microsoft Corporation. -class GenericPollOperation { - constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { - this.state = state; - this.lro = lro; - this.lroResourceLocationConfig = lroResourceLocationConfig; - this.processResult = processResult; - this.updateState = updateState; - this.isDone = isDone; - } - setPollerConfig(pollerConfig) { - this.pollerConfig = pollerConfig; - } - /** - * General update function for LROPoller, the general process is as follows - * 1. Check initial operation result to determine the strategy to use - * - Strategies: Location, Azure-AsyncOperation, Original Uri - * 2. Check if the operation result has a terminal state - * - Terminal state will be determined by each strategy - * 2.1 If it is terminal state Check if a final GET request is required, if so - * send final GET request and return result from operation. If no final GET - * is required, just return the result from operation. - * - Determining what to call for final request is responsibility of each strategy - * 2.2 If it is not terminal state, call the polling operation and go to step 1 - * - Determining what to call for polling is responsibility of each strategy - * - Strategies will always use the latest URI for polling if provided otherwise - * the last known one - */ - async update(options) { - var _a, _b, _c; - const state = this.state; - let lastResponse = undefined; - if (!state.isStarted) { - const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod); - lastResponse = await this.lro.sendInitialRequest(); - initializeState(lastResponse); - } - if (!state.isCompleted) { - if (!this.poll || !this.getLroStatusFromResponse) { - if (!state.config) { - throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed."); - } - const isDone = this.isDone; - this.getLroStatusFromResponse = isDone - ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) - : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig); - this.poll = createPoll(this.lro); - } - if (!state.pollingURL) { - throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed."); - } - const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse); - logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`); - if (currentState.done) { - state.result = this.processResult - ? this.processResult(currentState.flatResponse, state) - : currentState.flatResponse; - state.isCompleted = true; - } - else { - this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; - state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL); - } - lastResponse = currentState; - } - logger.verbose(`LRO: current state: ${JSON.stringify(state)}`); - if (lastResponse) { - (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); - } - else { - logger.error(`LRO: no response was received`); - } - (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); - return this; - } - async cancel() { - this.state.isCancelled = true; - return this; - } - /** - * Serializes the Poller operation. - */ - toString() { - return JSON.stringify({ - state: this.state, - }); - } -} - -// Copyright (c) Microsoft Corporation. -function deserializeState(serializedState) { - try { - return JSON.parse(serializedState).state; - } - catch (e) { - throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); - } -} /** * The LRO Engine, a class that performs polling. */ class LroEngine extends Poller { constructor(lro, options) { - const { intervalInMs = 2000, resumeFrom } = options || {}; + const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {}; const state = resumeFrom ? deserializeState(resumeFrom) : {}; - const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone); + const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone); super(operation); + this.resolveOnUnsuccessful = resolveOnUnsuccessful; this.config = { intervalInMs: intervalInMs }; operation.setPollerConfig(this.config); } @@ -15578,6 +15595,7 @@ exports.LroEngine = LroEngine; exports.Poller = Poller; exports.PollerCancelledError = PollerCancelledError; exports.PollerStoppedError = PollerStoppedError; +exports.createHttpPoller = createHttpPoller; //# sourceMappingURL=index.js.map @@ -15591,7 +15609,6 @@ exports.PollerStoppedError = PollerStoppedError; Object.defineProperty(exports, "__esModule", ({ value: true })); -__nccwpck_require__(2356); var tslib = __nccwpck_require__(6429); // Copyright (c) Microsoft Corporation. @@ -15613,47 +15630,78 @@ function getPagedAsyncIterator(pagedResult) { return this; }, byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => { - return getPageAsyncIterator(pagedResult, settings === null || settings === void 0 ? void 0 : settings.maxPageSize); + const { continuationToken, maxPageSize } = settings !== null && settings !== void 0 ? settings : {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + maxPageSize, + }); }), }; } -function getItemAsyncIterator(pagedResult, maxPageSize) { +function getItemAsyncIterator(pagedResult) { return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() { - var e_1, _a; - const pages = getPageAsyncIterator(pagedResult, maxPageSize); + var e_1, _a, e_2, _b; + const pages = getPageAsyncIterator(pagedResult); const firstVal = yield tslib.__await(pages.next()); // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is if (!Array.isArray(firstVal.value)) { - yield yield tslib.__await(firstVal.value); - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(firstVal.value)))); + try { + for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { + const page = pages_1_1.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(page)))); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); + } + finally { if (e_1) throw e_1.error; } + } + } + else { + yield yield tslib.__await(firstVal.value); + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); + } } else { yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value))); try { - for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { - const page = pages_1_1.value; + for (var pages_2 = tslib.__asyncValues(pages), pages_2_1; pages_2_1 = yield tslib.__await(pages_2.next()), !pages_2_1.done;) { + const page = pages_2_1.value; // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, // it must be the case that `TPage = TElement[]` yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page))); } } - catch (e_1_1) { e_1 = { error: e_1_1 }; } + catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { - if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); + if (pages_2_1 && !pages_2_1.done && (_b = pages_2.return)) yield tslib.__await(_b.call(pages_2)); } - finally { if (e_1) throw e_1.error; } + finally { if (e_2) throw e_2.error; } } } }); } -function getPageAsyncIterator(pagedResult, maxPageSize) { +function getPageAsyncIterator(pagedResult, options = {}) { return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() { - let response = yield tslib.__await(pagedResult.getPage(pagedResult.firstPageLink, maxPageSize)); + const { pageLink, maxPageSize } = options; + let response = yield tslib.__await(pagedResult.getPage(pageLink !== null && pageLink !== void 0 ? pageLink : pagedResult.firstPageLink, maxPageSize)); + if (!response) { + return yield tslib.__await(void 0); + } yield yield tslib.__await(response.page); while (response.nextPageLink) { response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); + if (!response) { + return yield tslib.__await(void 0); + } yield yield tslib.__await(response.page); } }); @@ -15668,7 +15716,7 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator; /***/ 6429: /***/ ((module) => { -/*! ***************************************************************************** +/****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -15688,6 +15736,10 @@ var __assign; var __rest; var __decorate; var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -15706,6 +15758,7 @@ var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; +var __classPrivateFieldIn; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; @@ -15774,6 +15827,51 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.push(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.push(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; @@ -15794,7 +15892,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (_) try { + while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -15822,7 +15920,11 @@ var __createBinding; __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -15902,7 +16004,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -15949,11 +16051,20 @@ var __createBinding; return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -15973,6 +16084,7 @@ var __createBinding; exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); }); @@ -16455,14 +16567,16 @@ exports.randomUUID = randomUUID; Object.defineProperty(exports, "__esModule", ({ value: true })); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var util = _interopDefault(__nccwpck_require__(3837)); var os = __nccwpck_require__(2037); +var util = __nccwpck_require__(3837); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var util__default = /*#__PURE__*/_interopDefaultLegacy(util); // Copyright (c) Microsoft Corporation. function log(message, ...args) { - process.stderr.write(`${util.format(message, ...args)}${os.EOL}`); + process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); } // Copyright (c) Microsoft Corporation. @@ -16480,7 +16594,7 @@ const debugObj = Object.assign((namespace) => { enable, enabled, disable, - log + log, }); function enable(namespaces) { enabledString = namespaces; @@ -16527,7 +16641,7 @@ function createDebugger(namespace) { destroy, log: debugObj.log, namespace, - extend + extend, }); function debug(...args) { if (!newDebugger.enabled) { @@ -16554,6 +16668,7 @@ function extend(namespace) { newDebugger.log = this.log; return newDebugger; } +var debug = debugObj; // Copyright (c) Microsoft Corporation. const registeredLoggers = new Set(); @@ -16564,9 +16679,9 @@ let azureLogLevel; * By default, logs are sent to stderr. * Override the `log` method to redirect logs to another location. */ -const AzureLogger = debugObj("azure"); +const AzureLogger = debug("azure"); AzureLogger.log = (...args) => { - debugObj.log(...args); + debug.log(...args); }; const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; if (logLevelFromEnv) { @@ -16579,7 +16694,7 @@ if (logLevelFromEnv) { } } /** - * Immediately enables logging at the specified log level. + * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. * @param level - The log level to enable for logging. * Options from most verbose to least verbose are: * - verbose @@ -16598,7 +16713,7 @@ function setLogLevel(level) { enabledNamespaces.push(logger.namespace); } } - debugObj.enable(enabledNamespaces.join(",")); + debug.enable(enabledNamespaces.join(",")); } /** * Retrieves the currently specified log level. @@ -16610,7 +16725,7 @@ const levelMap = { verbose: 400, info: 300, warning: 200, - error: 100 + error: 100, }; /** * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. @@ -16624,7 +16739,7 @@ function createClientLogger(namespace) { error: createLogger(clientRootLogger, "error"), warning: createLogger(clientRootLogger, "warning"), info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") + verbose: createLogger(clientRootLogger, "verbose"), }; } function patchLogMethod(parent, child) { @@ -16634,23 +16749,18 @@ function patchLogMethod(parent, child) { } function createLogger(parent, level) { const logger = Object.assign(parent.extend(level), { - level + level, }); patchLogMethod(parent, logger); if (shouldEnable(logger)) { - const enabledNamespaces = debugObj.disable(); - debugObj.enable(enabledNamespaces + "," + logger.namespace); + const enabledNamespaces = debug.disable(); + debug.enable(enabledNamespaces + "," + logger.namespace); } registeredLoggers.add(logger); return logger; } function shouldEnable(logger) { - if (azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]) { - return true; - } - else { - return false; - } + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); } function isAzureLogLevel(logLevel) { return AZURE_LOG_LEVELS.includes(logLevel); @@ -41791,7 +41901,7 @@ exports.newPipeline = newPipeline; /***/ 679: /***/ ((module) => { -/*! ***************************************************************************** +/****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -41811,6 +41921,10 @@ var __assign; var __rest; var __decorate; var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -41829,6 +41943,7 @@ var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; +var __classPrivateFieldIn; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; @@ -41897,6 +42012,51 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.push(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.push(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; @@ -41917,7 +42077,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (_) try { + while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -41945,7 +42105,11 @@ var __createBinding; __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -42025,7 +42189,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -42072,11 +42236,20 @@ var __createBinding; return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -42096,13 +42269,14 @@ var __createBinding; exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); }); /***/ }), /***/ 7171: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -42121,46 +42295,40 @@ var __createBinding; * See the License for the specific language governing permissions and * limitations under the License. */ -var __spreadArray = (this && this.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; -var NoopContextManager_1 = __nccwpck_require__(4118); -var global_utils_1 = __nccwpck_require__(5135); -var diag_1 = __nccwpck_require__(1877); -var API_NAME = 'context'; -var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); +const NoopContextManager_1 = __nccwpck_require__(4118); +const global_utils_1 = __nccwpck_require__(5135); +const diag_1 = __nccwpck_require__(1877); +const API_NAME = 'context'; +const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** * Singleton object which represents the entry point to the OpenTelemetry Context API */ -var ContextAPI = /** @class */ (function () { +class ContextAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ - function ContextAPI() { - } + constructor() { } /** Get the singleton instance of the Context API */ - ContextAPI.getInstance = function () { + static getInstance() { if (!this._instance) { this._instance = new ContextAPI(); } return this._instance; - }; + } /** * Set the current context manager. * * @returns true if the context manager was successfully registered, else false */ - ContextAPI.prototype.setGlobalContextManager = function (contextManager) { - return global_utils_1.registerGlobal(API_NAME, contextManager, diag_1.DiagAPI.instance()); - }; + setGlobalContextManager(contextManager) { + return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); + } /** * Get the currently active context */ - ContextAPI.prototype.active = function () { + active() { return this._getContextManager().active(); - }; + } /** * Execute a function with an active context * @@ -42169,33 +42337,27 @@ var ContextAPI = /** @class */ (function () { * @param thisArg optional receiver to be used for calling fn * @param args optional arguments forwarded to fn */ - ContextAPI.prototype.with = function (context, fn, thisArg) { - var _a; - var args = []; - for (var _i = 3; _i < arguments.length; _i++) { - args[_i - 3] = arguments[_i]; - } - return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], args)); - }; + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); + } /** * Bind a context to a target function or event emitter * * @param context context to bind to the event emitter or function. Defaults to the currently active context * @param target function or event emitter to bind */ - ContextAPI.prototype.bind = function (context, target) { + bind(context, target) { return this._getContextManager().bind(context, target); - }; - ContextAPI.prototype._getContextManager = function () { - return global_utils_1.getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER; - }; + } + _getContextManager() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; + } /** Disable and remove the global context manager */ - ContextAPI.prototype.disable = function () { + disable() { this._getContextManager().disable(); - global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); - }; - return ContextAPI; -}()); + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } +} exports.ContextAPI = ContextAPI; //# sourceMappingURL=context.js.map @@ -42223,62 +42385,63 @@ exports.ContextAPI = ContextAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; -var ComponentLogger_1 = __nccwpck_require__(7978); -var logLevelLogger_1 = __nccwpck_require__(9639); -var types_1 = __nccwpck_require__(8077); -var global_utils_1 = __nccwpck_require__(5135); -var API_NAME = 'diag'; +const ComponentLogger_1 = __nccwpck_require__(7978); +const logLevelLogger_1 = __nccwpck_require__(9639); +const types_1 = __nccwpck_require__(8077); +const global_utils_1 = __nccwpck_require__(5135); +const API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal * diagnostic API */ -var DiagAPI = /** @class */ (function () { +class DiagAPI { /** * Private internal constructor * @private */ - function DiagAPI() { + constructor() { function _logProxy(funcName) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var logger = global_utils_1.getGlobal('diag'); + return function (...args) { + const logger = (0, global_utils_1.getGlobal)('diag'); // shortcut if logger not set if (!logger) return; - return logger[funcName].apply(logger, args); + return logger[funcName](...args); }; } // Using self local variable for minification purposes as 'this' cannot be minified - var self = this; + const self = this; // DiagAPI specific functions - self.setLogger = function (logger, logLevel) { - var _a, _b; - if (logLevel === void 0) { logLevel = types_1.DiagLogLevel.INFO; } + const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { + var _a, _b, _c; if (logger === self) { // There isn't much we can do here. // Logging to the console might break the user application. // Try to log to self. If a logger was previously registered it will receive the log. - var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); return false; } - var oldLogger = global_utils_1.getGlobal('diag'); - var newLogger = logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger); + if (typeof optionsOrLogLevel === 'number') { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel, + }; + } + const oldLogger = (0, global_utils_1.getGlobal)('diag'); + const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); // There already is an logger registered. We'll let it know before overwriting it. - if (oldLogger) { - var stack = (_b = new Error().stack) !== null && _b !== void 0 ? _b : ''; - oldLogger.warn("Current logger will be overwritten from " + stack); - newLogger.warn("Current logger will overwrite one already registered from " + stack); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); } - return global_utils_1.registerGlobal('diag', newLogger, self, true); + return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); }; - self.disable = function () { - global_utils_1.unregisterGlobal(API_NAME, self); + self.setLogger = setLogger; + self.disable = () => { + (0, global_utils_1.unregisterGlobal)(API_NAME, self); }; - self.createComponentLogger = function (options) { + self.createComponentLogger = (options) => { return new ComponentLogger_1.DiagComponentLogger(options); }; self.verbose = _logProxy('verbose'); @@ -42288,19 +42451,86 @@ var DiagAPI = /** @class */ (function () { self.error = _logProxy('error'); } /** Get the singleton instance of the DiagAPI API */ - DiagAPI.instance = function () { + static instance() { if (!this._instance) { this._instance = new DiagAPI(); } return this._instance; - }; - return DiagAPI; -}()); + } +} exports.DiagAPI = DiagAPI; //# sourceMappingURL=diag.js.map /***/ }), +/***/ 7696: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MetricsAPI = void 0; +const NoopMeterProvider_1 = __nccwpck_require__(2647); +const global_utils_1 = __nccwpck_require__(5135); +const diag_1 = __nccwpck_require__(1877); +const API_NAME = 'metrics'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + /** Remove the global meter provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } +} +exports.MetricsAPI = MetricsAPI; +//# sourceMappingURL=metrics.js.map + +/***/ }), + /***/ 9909: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -42323,40 +42553,41 @@ exports.DiagAPI = DiagAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; -var global_utils_1 = __nccwpck_require__(5135); -var NoopTextMapPropagator_1 = __nccwpck_require__(2368); -var TextMapPropagator_1 = __nccwpck_require__(865); -var context_helpers_1 = __nccwpck_require__(7682); -var utils_1 = __nccwpck_require__(8136); -var diag_1 = __nccwpck_require__(1877); -var API_NAME = 'propagation'; -var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); +const global_utils_1 = __nccwpck_require__(5135); +const NoopTextMapPropagator_1 = __nccwpck_require__(2368); +const TextMapPropagator_1 = __nccwpck_require__(865); +const context_helpers_1 = __nccwpck_require__(7682); +const utils_1 = __nccwpck_require__(8136); +const diag_1 = __nccwpck_require__(1877); +const API_NAME = 'propagation'; +const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** * Singleton object which represents the entry point to the OpenTelemetry Propagation API */ -var PropagationAPI = /** @class */ (function () { +class PropagationAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ - function PropagationAPI() { + constructor() { this.createBaggage = utils_1.createBaggage; this.getBaggage = context_helpers_1.getBaggage; + this.getActiveBaggage = context_helpers_1.getActiveBaggage; this.setBaggage = context_helpers_1.setBaggage; this.deleteBaggage = context_helpers_1.deleteBaggage; } /** Get the singleton instance of the Propagator API */ - PropagationAPI.getInstance = function () { + static getInstance() { if (!this._instance) { this._instance = new PropagationAPI(); } return this._instance; - }; + } /** * Set the current propagator. * * @returns true if the propagator was successfully registered, else false */ - PropagationAPI.prototype.setGlobalPropagator = function (propagator) { - return global_utils_1.registerGlobal(API_NAME, propagator, diag_1.DiagAPI.instance()); - }; + setGlobalPropagator(propagator) { + return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); + } /** * Inject context into a carrier to be propagated inter-process * @@ -42364,10 +42595,9 @@ var PropagationAPI = /** @class */ (function () { * @param carrier carrier to inject context into * @param setter Function used to set values on the carrier */ - PropagationAPI.prototype.inject = function (context, carrier, setter) { - if (setter === void 0) { setter = TextMapPropagator_1.defaultTextMapSetter; } + inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { return this._getGlobalPropagator().inject(context, carrier, setter); - }; + } /** * Extract context from a carrier * @@ -42375,25 +42605,23 @@ var PropagationAPI = /** @class */ (function () { * @param carrier Carrier to extract context from * @param getter Function used to extract keys from a carrier */ - PropagationAPI.prototype.extract = function (context, carrier, getter) { - if (getter === void 0) { getter = TextMapPropagator_1.defaultTextMapGetter; } + extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { return this._getGlobalPropagator().extract(context, carrier, getter); - }; + } /** * Return a list of all fields which may be used by the propagator. */ - PropagationAPI.prototype.fields = function () { + fields() { return this._getGlobalPropagator().fields(); - }; + } /** Remove the global propagator */ - PropagationAPI.prototype.disable = function () { - global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); - }; - PropagationAPI.prototype._getGlobalPropagator = function () { - return global_utils_1.getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; - }; - return PropagationAPI; -}()); + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + _getGlobalPropagator() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + } +} exports.PropagationAPI = PropagationAPI; //# sourceMappingURL=propagation.js.map @@ -42421,65 +42649,65 @@ exports.PropagationAPI = PropagationAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; -var global_utils_1 = __nccwpck_require__(5135); -var ProxyTracerProvider_1 = __nccwpck_require__(2285); -var spancontext_utils_1 = __nccwpck_require__(9745); -var context_utils_1 = __nccwpck_require__(3326); -var diag_1 = __nccwpck_require__(1877); -var API_NAME = 'trace'; +const global_utils_1 = __nccwpck_require__(5135); +const ProxyTracerProvider_1 = __nccwpck_require__(2285); +const spancontext_utils_1 = __nccwpck_require__(9745); +const context_utils_1 = __nccwpck_require__(3326); +const diag_1 = __nccwpck_require__(1877); +const API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API */ -var TraceAPI = /** @class */ (function () { +class TraceAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ - function TraceAPI() { + constructor() { this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; this.deleteSpan = context_utils_1.deleteSpan; this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; this.getSpanContext = context_utils_1.getSpanContext; this.setSpan = context_utils_1.setSpan; this.setSpanContext = context_utils_1.setSpanContext; } /** Get the singleton instance of the Trace API */ - TraceAPI.getInstance = function () { + static getInstance() { if (!this._instance) { this._instance = new TraceAPI(); } return this._instance; - }; + } /** * Set the current global tracer. * * @returns true if the tracer provider was successfully registered, else false */ - TraceAPI.prototype.setGlobalTracerProvider = function (provider) { - var success = global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + setGlobalTracerProvider(provider) { + const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); if (success) { this._proxyTracerProvider.setDelegate(provider); } return success; - }; + } /** * Returns the global tracer provider. */ - TraceAPI.prototype.getTracerProvider = function () { - return global_utils_1.getGlobal(API_NAME) || this._proxyTracerProvider; - }; + getTracerProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; + } /** * Returns a tracer from the global tracer provider. */ - TraceAPI.prototype.getTracer = function (name, version) { + getTracer(name, version) { return this.getTracerProvider().getTracer(name, version); - }; + } /** Remove the global tracer provider */ - TraceAPI.prototype.disable = function () { - global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - }; - return TraceAPI; -}()); + } +} exports.TraceAPI = TraceAPI; //# sourceMappingURL=trace.js.map @@ -42506,12 +42734,13 @@ exports.TraceAPI = TraceAPI; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0; -var context_1 = __nccwpck_require__(8242); +exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; +const context_1 = __nccwpck_require__(7171); +const context_2 = __nccwpck_require__(8242); /** * Baggage key */ -var BAGGAGE_KEY = context_1.createContextKey('OpenTelemetry Baggage Key'); +const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); /** * Retrieve the current baggage from the given context * @@ -42522,6 +42751,15 @@ function getBaggage(context) { return context.getValue(BAGGAGE_KEY) || undefined; } exports.getBaggage = getBaggage; +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +function getActiveBaggage() { + return getBaggage(context_1.ContextAPI.getInstance().active()); +} +exports.getActiveBaggage = getActiveBaggage; /** * Store a baggage in the given context * @@ -42567,50 +42805,41 @@ exports.deleteBaggage = deleteBaggage; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaggageImpl = void 0; -var BaggageImpl = /** @class */ (function () { - function BaggageImpl(entries) { +class BaggageImpl { + constructor(entries) { this._entries = entries ? new Map(entries) : new Map(); } - BaggageImpl.prototype.getEntry = function (key) { - var entry = this._entries.get(key); + getEntry(key) { + const entry = this._entries.get(key); if (!entry) { return undefined; } return Object.assign({}, entry); - }; - BaggageImpl.prototype.getAllEntries = function () { - return Array.from(this._entries.entries()).map(function (_a) { - var k = _a[0], v = _a[1]; - return [k, v]; - }); - }; - BaggageImpl.prototype.setEntry = function (key, entry) { - var newBaggage = new BaggageImpl(this._entries); + } + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); newBaggage._entries.set(key, entry); return newBaggage; - }; - BaggageImpl.prototype.removeEntry = function (key) { - var newBaggage = new BaggageImpl(this._entries); + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); newBaggage._entries.delete(key); return newBaggage; - }; - BaggageImpl.prototype.removeEntries = function () { - var keys = []; - for (var _i = 0; _i < arguments.length; _i++) { - keys[_i] = arguments[_i]; - } - var newBaggage = new BaggageImpl(this._entries); - for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { - var key = keys_1[_a]; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { newBaggage._entries.delete(key); } return newBaggage; - }; - BaggageImpl.prototype.clear = function () { + } + clear() { return new BaggageImpl(); - }; - return BaggageImpl; -}()); + } +} exports.BaggageImpl = BaggageImpl; //# sourceMappingURL=baggage-impl.js.map @@ -42646,31 +42875,6 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); /***/ }), -/***/ 1508: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=types.js.map - -/***/ }), - /***/ 8136: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -42693,17 +42897,16 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -var diag_1 = __nccwpck_require__(1877); -var baggage_impl_1 = __nccwpck_require__(4811); -var symbol_1 = __nccwpck_require__(3542); -var diag = diag_1.DiagAPI.instance(); +const diag_1 = __nccwpck_require__(1877); +const baggage_impl_1 = __nccwpck_require__(4811); +const symbol_1 = __nccwpck_require__(3542); +const diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries * * @param entries An array of baggage entries the new baggage should contain */ -function createBaggage(entries) { - if (entries === void 0) { entries = {}; } +function createBaggage(entries = {}) { return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); } exports.createBaggage = createBaggage; @@ -42715,12 +42918,12 @@ exports.createBaggage = createBaggage; */ function baggageEntryMetadataFromString(str) { if (typeof str !== 'string') { - diag.error("Cannot create baggage metadata from unknown type: " + typeof str); + diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); str = ''; } return { __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString: function () { + toString() { return str; }, }; @@ -42730,8 +42933,8 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; /***/ }), -/***/ 4447: -/***/ ((__unused_webpack_module, exports) => { +/***/ 7393: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -42751,22 +42954,18 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=Exception.js.map - -/***/ }), - -/***/ 2358: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=Time.js.map +exports.context = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_1 = __nccwpck_require__(7171); +/** Entrypoint for context API */ +exports.context = context_1.ContextAPI.getInstance(); +//# sourceMappingURL=context-api.js.map /***/ }), /***/ 4118: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -42785,38 +42984,26 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * See the License for the specific language governing permissions and * limitations under the License. */ -var __spreadArray = (this && this.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; -var context_1 = __nccwpck_require__(8242); -var NoopContextManager = /** @class */ (function () { - function NoopContextManager() { - } - NoopContextManager.prototype.active = function () { +const context_1 = __nccwpck_require__(8242); +class NoopContextManager { + active() { return context_1.ROOT_CONTEXT; - }; - NoopContextManager.prototype.with = function (_context, fn, thisArg) { - var args = []; - for (var _i = 3; _i < arguments.length; _i++) { - args[_i - 3] = arguments[_i]; - } - return fn.call.apply(fn, __spreadArray([thisArg], args)); - }; - NoopContextManager.prototype.bind = function (_context, target) { + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { return target; - }; - NoopContextManager.prototype.enable = function () { + } + enable() { return this; - }; - NoopContextManager.prototype.disable = function () { + } + disable() { return this; - }; - return NoopContextManager; -}()); + } +} exports.NoopContextManager = NoopContextManager; //# sourceMappingURL=NoopContextManager.js.map @@ -42855,38 +43042,37 @@ function createContextKey(description) { return Symbol.for(description); } exports.createContextKey = createContextKey; -var BaseContext = /** @class */ (function () { +class BaseContext { /** * Construct a new context which inherits values from an optional parent context. * * @param parentContext a context from which to inherit values */ - function BaseContext(parentContext) { + constructor(parentContext) { // for minification - var self = this; + const self = this; self._currentContext = parentContext ? new Map(parentContext) : new Map(); - self.getValue = function (key) { return self._currentContext.get(key); }; - self.setValue = function (key, value) { - var context = new BaseContext(self._currentContext); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context = new BaseContext(self._currentContext); context._currentContext.set(key, value); return context; }; - self.deleteValue = function (key) { - var context = new BaseContext(self._currentContext); + self.deleteValue = (key) => { + const context = new BaseContext(self._currentContext); context._currentContext.delete(key); return context; }; } - return BaseContext; -}()); +} /** The root context is used as the default parent context when there is no active context */ exports.ROOT_CONTEXT = new BaseContext(); //# sourceMappingURL=context.js.map /***/ }), -/***/ 6504: -/***/ ((__unused_webpack_module, exports) => { +/***/ 9721: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -42906,7 +43092,18 @@ exports.ROOT_CONTEXT = new BaseContext(); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=types.js.map +exports.diag = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const diag_1 = __nccwpck_require__(1877); +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +exports.diag = diag_1.DiagAPI.instance(); +//# sourceMappingURL=diag-api.js.map /***/ }), @@ -42932,7 +43129,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; -var global_utils_1 = __nccwpck_require__(5135); +const global_utils_1 = __nccwpck_require__(5135); /** * Component Logger which is meant to be used as part of any component which * will add automatically additional namespace in front of the log message. @@ -42942,56 +43139,35 @@ var global_utils_1 = __nccwpck_require__(5135); * cLogger.debug('test'); * // @opentelemetry/instrumentation-http test */ -var DiagComponentLogger = /** @class */ (function () { - function DiagComponentLogger(props) { +class DiagComponentLogger { + constructor(props) { this._namespace = props.namespace || 'DiagComponentLogger'; } - DiagComponentLogger.prototype.debug = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + debug(...args) { return logProxy('debug', this._namespace, args); - }; - DiagComponentLogger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + } + error(...args) { return logProxy('error', this._namespace, args); - }; - DiagComponentLogger.prototype.info = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + } + info(...args) { return logProxy('info', this._namespace, args); - }; - DiagComponentLogger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + } + warn(...args) { return logProxy('warn', this._namespace, args); - }; - DiagComponentLogger.prototype.verbose = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + } + verbose(...args) { return logProxy('verbose', this._namespace, args); - }; - return DiagComponentLogger; -}()); + } +} exports.DiagComponentLogger = DiagComponentLogger; function logProxy(funcName, namespace, args) { - var logger = global_utils_1.getGlobal('diag'); + const logger = (0, global_utils_1.getGlobal)('diag'); // shortcut if logger not set if (!logger) { return; } args.unshift(namespace); - return logger[funcName].apply(logger, args); + return logger[funcName](...args); } //# sourceMappingURL=ComponentLogger.js.map @@ -43019,7 +43195,7 @@ function logProxy(funcName, namespace, args) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagConsoleLogger = void 0; -var consoleMap = [ +const consoleMap = [ { n: 'error', c: 'error' }, { n: 'warn', c: 'warn' }, { n: 'info', c: 'info' }, @@ -43031,18 +43207,14 @@ var consoleMap = [ * If you want to limit the amount of logging to a specific level or lower use the * {@link createLogLevelDiagLogger} */ -var DiagConsoleLogger = /** @class */ (function () { - function DiagConsoleLogger() { +class DiagConsoleLogger { + constructor() { function _consoleFunc(funcName) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + return function (...args) { if (console) { // Some environments only expose the console when the F12 developer console is open // eslint-disable-next-line no-console - var theFunc = console[funcName]; + let theFunc = console[funcName]; if (typeof theFunc !== 'function') { // Not all environments support all functions // eslint-disable-next-line no-console @@ -43055,54 +43227,16 @@ var DiagConsoleLogger = /** @class */ (function () { } }; } - for (var i = 0; i < consoleMap.length; i++) { + for (let i = 0; i < consoleMap.length; i++) { this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); } } - return DiagConsoleLogger; -}()); +} exports.DiagConsoleLogger = DiagConsoleLogger; //# sourceMappingURL=consoleLogger.js.map /***/ }), -/***/ 1634: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(3041), exports); -__exportStar(__nccwpck_require__(8077), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - /***/ 9639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -43125,7 +43259,7 @@ __exportStar(__nccwpck_require__(8077), exports); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; -var types_1 = __nccwpck_require__(8077); +const types_1 = __nccwpck_require__(8077); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; @@ -43136,7 +43270,7 @@ function createLogLevelDiagLogger(maxLevel, logger) { // In case the logger is null or undefined logger = logger || {}; function _filterFunc(funcName, theLevel) { - var theFunc = logger[funcName]; + const theFunc = logger[funcName]; if (typeof theFunc === 'function' && maxLevel >= theLevel) { return theFunc.bind(logger); } @@ -43207,7 +43341,7 @@ var DiagLogLevel; /***/ }), /***/ 5163: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -43226,40 +43360,42 @@ var DiagLogLevel; * See the License for the specific language governing permissions and * limitations under the License. */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.baggageEntryMetadataFromString = void 0; -__exportStar(__nccwpck_require__(1508), exports); +exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; var utils_1 = __nccwpck_require__(8136); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); -__exportStar(__nccwpck_require__(4447), exports); -__exportStar(__nccwpck_require__(2358), exports); -__exportStar(__nccwpck_require__(1634), exports); -__exportStar(__nccwpck_require__(865), exports); -__exportStar(__nccwpck_require__(7492), exports); -__exportStar(__nccwpck_require__(4023), exports); -__exportStar(__nccwpck_require__(3503), exports); -__exportStar(__nccwpck_require__(2285), exports); -__exportStar(__nccwpck_require__(9671), exports); -__exportStar(__nccwpck_require__(3209), exports); -__exportStar(__nccwpck_require__(5769), exports); -__exportStar(__nccwpck_require__(1424), exports); -__exportStar(__nccwpck_require__(4416), exports); -__exportStar(__nccwpck_require__(955), exports); -__exportStar(__nccwpck_require__(8845), exports); -__exportStar(__nccwpck_require__(6905), exports); -__exportStar(__nccwpck_require__(8384), exports); -__exportStar(__nccwpck_require__(891), exports); -__exportStar(__nccwpck_require__(3168), exports); +// Context APIs +var context_1 = __nccwpck_require__(8242); +Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); +Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); +// Diag APIs +var consoleLogger_1 = __nccwpck_require__(3041); +Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); +var types_1 = __nccwpck_require__(8077); +Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); +// Metrics APIs +var NoopMeter_1 = __nccwpck_require__(4837); +Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); +var Metric_1 = __nccwpck_require__(9999); +Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); +// Propagation APIs +var TextMapPropagator_1 = __nccwpck_require__(865); +Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); +Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); +var ProxyTracer_1 = __nccwpck_require__(3503); +Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); +var ProxyTracerProvider_1 = __nccwpck_require__(2285); +Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); +var SamplingResult_1 = __nccwpck_require__(3209); +Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); +var span_kind_1 = __nccwpck_require__(1424); +Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); +var status_1 = __nccwpck_require__(8845); +Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); +var trace_flags_1 = __nccwpck_require__(6905); +Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); +var utils_2 = __nccwpck_require__(2615); +Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); var spancontext_utils_1 = __nccwpck_require__(9745); Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); @@ -43268,30 +43404,25 @@ var invalid_span_constants_1 = __nccwpck_require__(1760); Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); -__exportStar(__nccwpck_require__(8242), exports); -__exportStar(__nccwpck_require__(6504), exports); -var context_1 = __nccwpck_require__(7171); -/** Entrypoint for context API */ -exports.context = context_1.ContextAPI.getInstance(); -var trace_1 = __nccwpck_require__(1539); -/** Entrypoint for trace API */ -exports.trace = trace_1.TraceAPI.getInstance(); -var propagation_1 = __nccwpck_require__(9909); -/** Entrypoint for propagation API */ -exports.propagation = propagation_1.PropagationAPI.getInstance(); -var diag_1 = __nccwpck_require__(1877); -/** - * Entrypoint for Diag API. - * Defines Diagnostic handler used for internal diagnostic logging operations. - * The default provides a Noop DiagLogger implementation which may be changed via the - * diag.setLogger(logger: DiagLogger) function. - */ -exports.diag = diag_1.DiagAPI.instance(); +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_api_1 = __nccwpck_require__(7393); +Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); +const diag_api_1 = __nccwpck_require__(9721); +Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); +const metrics_api_1 = __nccwpck_require__(2601); +Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); +const propagation_api_1 = __nccwpck_require__(7591); +Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); +const trace_api_1 = __nccwpck_require__(8989); +Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); +// Default export. exports["default"] = { - trace: exports.trace, - context: exports.context, - propagation: exports.propagation, - diag: exports.diag, + context: context_api_1.context, + diag: diag_api_1.diag, + metrics: metrics_api_1.metrics, + propagation: propagation_api_1.propagation, + trace: trace_api_1.trace, }; //# sourceMappingURL=index.js.map @@ -43319,47 +43450,46 @@ exports["default"] = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -var platform_1 = __nccwpck_require__(9957); -var version_1 = __nccwpck_require__(8996); -var semver_1 = __nccwpck_require__(1522); -var major = version_1.VERSION.split('.')[0]; -var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); -var _global = platform_1._globalThis; -function registerGlobal(type, instance, diag, allowOverride) { +const platform_1 = __nccwpck_require__(9957); +const version_1 = __nccwpck_require__(8996); +const semver_1 = __nccwpck_require__(1522); +const major = version_1.VERSION.split('.')[0]; +const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); +const _global = platform_1._globalThis; +function registerGlobal(type, instance, diag, allowOverride = false) { var _a; - if (allowOverride === void 0) { allowOverride = false; } - var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: version_1.VERSION, }); if (!allowOverride && api[type]) { // already registered an API of this type - var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); diag.error(err.stack || err.message); return false; } if (api.version !== version_1.VERSION) { // All registered APIs must be of the same version exactly - var err = new Error('@opentelemetry/api: All API registration versions must match'); + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); diag.error(err.stack || err.message); return false; } api[type] = instance; - diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + version_1.VERSION + "."); + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); return true; } exports.registerGlobal = registerGlobal; function getGlobal(type) { var _a, _b; - var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; - if (!globalVersion || !semver_1.isCompatible(globalVersion)) { + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { return; } return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } exports.getGlobal = getGlobal; function unregisterGlobal(type, diag) { - diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + version_1.VERSION + "."); - var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; } @@ -43391,8 +43521,8 @@ exports.unregisterGlobal = unregisterGlobal; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; -var version_1 = __nccwpck_require__(8996); -var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +const version_1 = __nccwpck_require__(8996); +const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. * @@ -43410,14 +43540,14 @@ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; * @param ownVersion version which should be checked against */ function _makeCompatibilityCheck(ownVersion) { - var acceptedVersions = new Set([ownVersion]); - var rejectedVersions = new Set(); - var myVersionMatch = ownVersion.match(re); + const acceptedVersions = new Set([ownVersion]); + const rejectedVersions = new Set(); + const myVersionMatch = ownVersion.match(re); if (!myVersionMatch) { // we cannot guarantee compatibility so we always return noop - return function () { return false; }; + return () => false; } - var ownVersionParsed = { + const ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], @@ -43444,13 +43574,13 @@ function _makeCompatibilityCheck(ownVersion) { if (rejectedVersions.has(globalVersion)) { return false; } - var globalVersionMatch = globalVersion.match(re); + const globalVersionMatch = globalVersion.match(re); if (!globalVersionMatch) { // cannot parse other version // we cannot guarantee compatibility so we always noop return _reject(globalVersion); } - var globalVersionParsed = { + const globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], @@ -43498,6 +43628,230 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); /***/ }), +/***/ 2601: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.metrics = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const metrics_1 = __nccwpck_require__(7696); +/** Entrypoint for metrics API */ +exports.metrics = metrics_1.MetricsAPI.getInstance(); +//# sourceMappingURL=metrics-api.js.map + +/***/ }), + +/***/ 9999: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ValueType = void 0; +/** The Type of value. It describes how the data is reported. */ +var ValueType; +(function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; +})(ValueType = exports.ValueType || (exports.ValueType = {})); +//# sourceMappingURL=Metric.js.map + +/***/ }), + +/***/ 4837: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +class NoopMeter { + constructor() { } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return exports.NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return exports.NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return exports.NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return exports.NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { } +} +exports.NoopMeter = NoopMeter; +class NoopMetric { +} +exports.NoopMetric = NoopMetric; +class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopCounterMetric = NoopCounterMetric; +class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; +class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) { } +} +exports.NoopHistogramMetric = NoopHistogramMetric; +class NoopObservableMetric { + addCallback(_callback) { } + removeCallback(_callback) { } +} +exports.NoopObservableMetric = NoopObservableMetric; +class NoopObservableCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableCounterMetric = NoopObservableCounterMetric; +class NoopObservableGaugeMetric extends NoopObservableMetric { +} +exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; +class NoopObservableUpDownCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; +exports.NOOP_METER = new NoopMeter(); +// Synchronous instruments +exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); +exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); +exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); +// Asynchronous instruments +exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); +exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); +exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); +/** + * Create a no-op Meter + */ +function createNoopMeter() { + return exports.NOOP_METER; +} +exports.createNoopMeter = createNoopMeter; +//# sourceMappingURL=NoopMeter.js.map + +/***/ }), + +/***/ 2647: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; +const NoopMeter_1 = __nccwpck_require__(4837); +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NoopMeter_1.NOOP_METER; + } +} +exports.NoopMeterProvider = NoopMeterProvider; +exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); +//# sourceMappingURL=NoopMeterProvider.js.map + +/***/ }), + /***/ 9957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -43599,6 +43953,37 @@ __exportStar(__nccwpck_require__(9406), exports); /***/ }), +/***/ 7591: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.propagation = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const propagation_1 = __nccwpck_require__(9909); +/** Entrypoint for propagation API */ +exports.propagation = propagation_1.PropagationAPI.getInstance(); +//# sourceMappingURL=propagation-api.js.map + +/***/ }), + /***/ 2368: /***/ ((__unused_webpack_module, exports) => { @@ -43624,20 +44009,17 @@ exports.NoopTextMapPropagator = void 0; /** * No-op implementations of {@link TextMapPropagator}. */ -var NoopTextMapPropagator = /** @class */ (function () { - function NoopTextMapPropagator() { - } +class NoopTextMapPropagator { /** Noop inject function does nothing */ - NoopTextMapPropagator.prototype.inject = function (_context, _carrier) { }; + inject(_context, _carrier) { } /** Noop extract function does nothing and returns the input context */ - NoopTextMapPropagator.prototype.extract = function (context, _carrier) { + extract(context, _carrier) { return context; - }; - NoopTextMapPropagator.prototype.fields = function () { + } + fields() { return []; - }; - return NoopTextMapPropagator; -}()); + } +} exports.NoopTextMapPropagator = NoopTextMapPropagator; //# sourceMappingURL=NoopTextMapPropagator.js.map @@ -43666,13 +44048,13 @@ exports.NoopTextMapPropagator = NoopTextMapPropagator; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; exports.defaultTextMapGetter = { - get: function (carrier, key) { + get(carrier, key) { if (carrier == null) { return undefined; } return carrier[key]; }, - keys: function (carrier) { + keys(carrier) { if (carrier == null) { return []; } @@ -43680,7 +44062,7 @@ exports.defaultTextMapGetter = { }, }; exports.defaultTextMapSetter = { - set: function (carrier, key, value) { + set(carrier, key, value) { if (carrier == null) { return; } @@ -43691,6 +44073,37 @@ exports.defaultTextMapSetter = { /***/ }), +/***/ 8989: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.trace = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const trace_1 = __nccwpck_require__(1539); +/** Entrypoint for trace API */ +exports.trace = trace_1.TraceAPI.getInstance(); +//# sourceMappingURL=trace-api.js.map + +/***/ }), + /***/ 1462: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -43713,51 +44126,49 @@ exports.defaultTextMapSetter = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; -var invalid_span_constants_1 = __nccwpck_require__(1760); +const invalid_span_constants_1 = __nccwpck_require__(1760); /** * The NonRecordingSpan is the default {@link Span} that is used when no Span * implementation is available. All operations are no-op including context * propagation. */ -var NonRecordingSpan = /** @class */ (function () { - function NonRecordingSpan(_spanContext) { - if (_spanContext === void 0) { _spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT; } +class NonRecordingSpan { + constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { this._spanContext = _spanContext; } // Returns a SpanContext. - NonRecordingSpan.prototype.spanContext = function () { + spanContext() { return this._spanContext; - }; + } // By default does nothing - NonRecordingSpan.prototype.setAttribute = function (_key, _value) { + setAttribute(_key, _value) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.setAttributes = function (_attributes) { + setAttributes(_attributes) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.addEvent = function (_name, _attributes) { + addEvent(_name, _attributes) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.setStatus = function (_status) { + setStatus(_status) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.updateName = function (_name) { + updateName(_name) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.end = function (_endTime) { }; + end(_endTime) { } // isRecording always returns false for NonRecordingSpan. - NonRecordingSpan.prototype.isRecording = function () { + isRecording() { return false; - }; + } // By default does nothing - NonRecordingSpan.prototype.recordException = function (_exception, _time) { }; - return NonRecordingSpan; -}()); + recordException(_exception, _time) { } +} exports.NonRecordingSpan = NonRecordingSpan; //# sourceMappingURL=NonRecordingSpan.js.map @@ -43785,36 +44196,34 @@ exports.NonRecordingSpan = NonRecordingSpan; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; -var context_1 = __nccwpck_require__(7171); -var context_utils_1 = __nccwpck_require__(3326); -var NonRecordingSpan_1 = __nccwpck_require__(1462); -var spancontext_utils_1 = __nccwpck_require__(9745); -var context = context_1.ContextAPI.getInstance(); +const context_1 = __nccwpck_require__(7171); +const context_utils_1 = __nccwpck_require__(3326); +const NonRecordingSpan_1 = __nccwpck_require__(1462); +const spancontext_utils_1 = __nccwpck_require__(9745); +const contextApi = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. */ -var NoopTracer = /** @class */ (function () { - function NoopTracer() { - } +class NoopTracer { // startSpan starts a noop span. - NoopTracer.prototype.startSpan = function (name, options, context) { - var root = Boolean(options === null || options === void 0 ? void 0 : options.root); + startSpan(name, options, context = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan_1.NonRecordingSpan(); } - var parentFromContext = context && context_utils_1.getSpanContext(context); + const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); if (isSpanContext(parentFromContext) && - spancontext_utils_1.isSpanContextValid(parentFromContext)) { + (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); } else { return new NonRecordingSpan_1.NonRecordingSpan(); } - }; - NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { - var opts; - var ctx; - var fn; + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; if (arguments.length < 2) { return; } @@ -43830,13 +44239,12 @@ var NoopTracer = /** @class */ (function () { ctx = arg3; fn = arg4; } - var parentContext = ctx !== null && ctx !== void 0 ? ctx : context.active(); - var span = this.startSpan(name, opts, parentContext); - var contextWithSpanSet = context_utils_1.setSpan(parentContext, span); - return context.with(contextWithSpanSet, fn, undefined, span); - }; - return NoopTracer; -}()); + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); + } +} exports.NoopTracer = NoopTracer; function isSpanContext(spanContext) { return (typeof spanContext === 'object' && @@ -43870,21 +44278,18 @@ function isSpanContext(spanContext) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; -var NoopTracer_1 = __nccwpck_require__(7606); +const NoopTracer_1 = __nccwpck_require__(7606); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. * * All operations are no-op. */ -var NoopTracerProvider = /** @class */ (function () { - function NoopTracerProvider() { - } - NoopTracerProvider.prototype.getTracer = function (_name, _version) { +class NoopTracerProvider { + getTracer(_name, _version, _options) { return new NoopTracer_1.NoopTracer(); - }; - return NoopTracerProvider; -}()); + } +} exports.NoopTracerProvider = NoopTracerProvider; //# sourceMappingURL=NoopTracerProvider.js.map @@ -43912,41 +44317,41 @@ exports.NoopTracerProvider = NoopTracerProvider; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; -var NoopTracer_1 = __nccwpck_require__(7606); -var NOOP_TRACER = new NoopTracer_1.NoopTracer(); +const NoopTracer_1 = __nccwpck_require__(7606); +const NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider */ -var ProxyTracer = /** @class */ (function () { - function ProxyTracer(_provider, name, version) { +class ProxyTracer { + constructor(_provider, name, version, options) { this._provider = _provider; this.name = name; this.version = version; + this.options = options; } - ProxyTracer.prototype.startSpan = function (name, options, context) { + startSpan(name, options, context) { return this._getTracer().startSpan(name, options, context); - }; - ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) { - var tracer = this._getTracer(); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); - }; + } /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. */ - ProxyTracer.prototype._getTracer = function () { + _getTracer() { if (this._delegate) { return this._delegate; } - var tracer = this._provider.getDelegateTracer(this.name, this.version); + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER; } this._delegate = tracer; return this._delegate; - }; - return ProxyTracer; -}()); + } +} exports.ProxyTracer = ProxyTracer; //# sourceMappingURL=ProxyTracer.js.map @@ -43974,9 +44379,9 @@ exports.ProxyTracer = ProxyTracer; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; -var ProxyTracer_1 = __nccwpck_require__(3503); -var NoopTracerProvider_1 = __nccwpck_require__(3259); -var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); +const ProxyTracer_1 = __nccwpck_require__(3503); +const NoopTracerProvider_1 = __nccwpck_require__(3259); +const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. * @@ -43985,62 +44390,34 @@ var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); * When a delegate is set after tracers have already been provided, * all tracers already provided will use the provided delegate implementation. */ -var ProxyTracerProvider = /** @class */ (function () { - function ProxyTracerProvider() { - } +class ProxyTracerProvider { /** * Get a {@link ProxyTracer} */ - ProxyTracerProvider.prototype.getTracer = function (name, version) { + getTracer(name, version, options) { var _a; - return ((_a = this.getDelegateTracer(name, version)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version)); - }; - ProxyTracerProvider.prototype.getDelegate = function () { + return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); + } + getDelegate() { var _a; return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; - }; + } /** * Set the delegate tracer provider */ - ProxyTracerProvider.prototype.setDelegate = function (delegate) { + setDelegate(delegate) { this._delegate = delegate; - }; - ProxyTracerProvider.prototype.getDelegateTracer = function (name, version) { + } + getDelegateTracer(name, version, options) { var _a; - return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version); - }; - return ProxyTracerProvider; -}()); + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); + } +} exports.ProxyTracerProvider = ProxyTracerProvider; //# sourceMappingURL=ProxyTracerProvider.js.map /***/ }), -/***/ 9671: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=Sampler.js.map - -/***/ }), - /***/ 3209: /***/ ((__unused_webpack_module, exports) => { @@ -44064,6 +44441,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SamplingDecision = void 0; /** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. * A sampling decision that determines how a {@link Span} will be recorded * and collected. */ @@ -44089,56 +44467,6 @@ var SamplingDecision; /***/ }), -/***/ 955: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=SpanOptions.js.map - -/***/ }), - -/***/ 7492: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=attributes.js.map - -/***/ }), - /***/ 3326: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -44160,13 +44488,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0; -var context_1 = __nccwpck_require__(8242); -var NonRecordingSpan_1 = __nccwpck_require__(1462); +exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; +const context_1 = __nccwpck_require__(8242); +const NonRecordingSpan_1 = __nccwpck_require__(1462); +const context_2 = __nccwpck_require__(7171); /** * span key */ -var SPAN_KEY = context_1.createContextKey('OpenTelemetry Context Key SPAN'); +const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); /** * Return the span if one exists * @@ -44176,6 +44505,13 @@ function getSpan(context) { return context.getValue(SPAN_KEY) || undefined; } exports.getSpan = getSpan; +/** + * Gets the span from the current context, if one exists. + */ +function getActiveSpan() { + return getSpan(context_2.ContextAPI.getInstance().active()); +} +exports.getActiveSpan = getActiveSpan; /** * Set the span on a context * @@ -44220,7 +44556,7 @@ exports.getSpanContext = getSpanContext; /***/ }), -/***/ 1760: +/***/ 2110: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44241,20 +44577,96 @@ exports.getSpanContext = getSpanContext; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -var trace_flags_1 = __nccwpck_require__(6905); -exports.INVALID_SPANID = '0000000000000000'; -exports.INVALID_TRACEID = '00000000000000000000000000000000'; -exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, -}; -//# sourceMappingURL=invalid-span-constants.js.map +exports.TraceStateImpl = void 0; +const tracestate_validators_1 = __nccwpck_require__(4864); +const MAX_TRACE_STATE_ITEMS = 32; +const MAX_TRACE_STATE_LEN = 512; +const LIST_MEMBERS_SEPARATOR = ','; +const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys() + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { + agg.set(key, value); + } + else { + // TODO: Consider to add warning log + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } +} +exports.TraceStateImpl = TraceStateImpl; +//# sourceMappingURL=tracestate-impl.js.map /***/ }), -/***/ 4023: +/***/ 4864: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -44275,12 +44687,40 @@ exports.INVALID_SPAN_CONTEXT = { * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=link.js.map +exports.validateValue = exports.validateKey = void 0; +const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; +const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; +const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; +const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); +const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +exports.validateKey = validateKey; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); +} +exports.validateValue = validateValue; +//# sourceMappingURL=tracestate-validators.js.map /***/ }), -/***/ 4416: -/***/ ((__unused_webpack_module, exports) => { +/***/ 2615: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44300,12 +44740,18 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=span.js.map +exports.createTraceState = void 0; +const tracestate_impl_1 = __nccwpck_require__(2110); +function createTraceState(rawTraceState) { + return new tracestate_impl_1.TraceStateImpl(rawTraceState); +} +exports.createTraceState = createTraceState; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 5769: -/***/ ((__unused_webpack_module, exports) => { +/***/ 1760: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44325,7 +44771,16 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=span_context.js.map +exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +const trace_flags_1 = __nccwpck_require__(6905); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map /***/ }), @@ -44404,10 +44859,10 @@ exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = e * See the License for the specific language governing permissions and * limitations under the License. */ -var invalid_span_constants_1 = __nccwpck_require__(1760); -var NonRecordingSpan_1 = __nccwpck_require__(1462); -var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; -var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +const invalid_span_constants_1 = __nccwpck_require__(1760); +const NonRecordingSpan_1 = __nccwpck_require__(1462); +const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; } @@ -44501,81 +44956,6 @@ var TraceFlags; /***/ }), -/***/ 8384: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=trace_state.js.map - -/***/ }), - -/***/ 3168: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=tracer.js.map - -/***/ }), - -/***/ 891: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=tracer_provider.js.map - -/***/ }), - /***/ 8996: /***/ ((__unused_webpack_module, exports) => { @@ -44599,7 +44979,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.0.4'; +exports.VERSION = '1.4.1'; //# sourceMappingURL=version.js.map /***/ }), diff --git a/dist/setup/index.js b/dist/setup/index.js index c86bcfb5d..6e74066e1 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -9630,19 +9630,18 @@ function _getGlobal(key, defaultValue) { /***/ }), /***/ 2557: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib = __nccwpck_require__(9268); - // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var listenersMap = new WeakMap(); -var abortedMap = new WeakMap(); +/// +const listenersMap = new WeakMap(); +const abortedMap = new WeakMap(); /** * An aborter instance implements AbortSignal interface, can abort HTTP requests. * @@ -9656,8 +9655,8 @@ var abortedMap = new WeakMap(); * await doAsyncWork(AbortSignal.none); * ``` */ -var AbortSignal = /** @class */ (function () { - function AbortSignal() { +class AbortSignal { + constructor() { /** * onabort event listener. */ @@ -9665,74 +9664,65 @@ var AbortSignal = /** @class */ (function () { listenersMap.set(this, []); abortedMap.set(this, false); } - Object.defineProperty(AbortSignal.prototype, "aborted", { - /** - * Status of whether aborted or not. - * - * @readonly - */ - get: function () { - if (!abortedMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - return abortedMap.get(this); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AbortSignal, "none", { - /** - * Creates a new AbortSignal instance that will never be aborted. - * - * @readonly - */ - get: function () { - return new AbortSignal(); - }, - enumerable: false, - configurable: true - }); + /** + * Status of whether aborted or not. + * + * @readonly + */ + get aborted() { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + return abortedMap.get(this); + } + /** + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + */ + static get none() { + return new AbortSignal(); + } /** * Added new "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be added */ - AbortSignal.prototype.addEventListener = function ( + addEventListener( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - var listeners = listenersMap.get(this); + const listeners = listenersMap.get(this); listeners.push(listener); - }; + } /** * Remove "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be removed */ - AbortSignal.prototype.removeEventListener = function ( + removeEventListener( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - var listeners = listenersMap.get(this); - var index = listeners.indexOf(listener); + const listeners = listenersMap.get(this); + const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } - }; + } /** * Dispatches a synthetic event to the AbortSignal. */ - AbortSignal.prototype.dispatchEvent = function (_event) { + dispatchEvent(_event) { throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); - }; - return AbortSignal; -}()); + } +} /** * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. * Will try to trigger abort event for all linked AbortSignal nodes. @@ -9750,12 +9740,12 @@ function abortSignal(signal) { if (signal.onabort) { signal.onabort.call(signal); } - var listeners = listenersMap.get(signal); + const listeners = listenersMap.get(signal); if (listeners) { // Create a copy of listeners so mutations to the array // (e.g. via removeListener calls) don't affect the listeners // we invoke. - listeners.slice().forEach(function (listener) { + listeners.slice().forEach((listener) => { listener.call(signal, { type: "abort" }); }); } @@ -9781,15 +9771,12 @@ function abortSignal(signal) { * } * ``` */ -var AbortError = /** @class */ (function (_super) { - tslib.__extends(AbortError, _super); - function AbortError(message) { - var _this = _super.call(this, message) || this; - _this.name = "AbortError"; - return _this; +class AbortError extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } - return AbortError; -}(Error)); +} /** * An AbortController provides an AbortSignal and the associated controls to signal * that an asynchronous operation should be aborted. @@ -9824,10 +9811,9 @@ var AbortError = /** @class */ (function (_super) { * await doAsyncWork(aborter.withTimeout(25 * 1000)); * ``` */ -var AbortController = /** @class */ (function () { +class AbortController { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - function AbortController(parentSignals) { - var _this = this; + constructor(parentSignals) { this._signal = new AbortSignal(); if (!parentSignals) { return; @@ -9837,8 +9823,7 @@ var AbortController = /** @class */ (function () { // eslint-disable-next-line prefer-rest-params parentSignals = arguments; } - for (var _i = 0, parentSignals_1 = parentSignals; _i < parentSignals_1.length; _i++) { - var parentSignal = parentSignals_1[_i]; + for (const parentSignal of parentSignals) { // if the parent signal has already had abort() called, // then call abort on this signal as well. if (parentSignal.aborted) { @@ -9846,47 +9831,42 @@ var AbortController = /** @class */ (function () { } else { // when the parent signal aborts, this signal should as well. - parentSignal.addEventListener("abort", function () { - _this.abort(); + parentSignal.addEventListener("abort", () => { + this.abort(); }); } } } - Object.defineProperty(AbortController.prototype, "signal", { - /** - * The AbortSignal associated with this controller that will signal aborted - * when the abort method is called on this controller. - * - * @readonly - */ - get: function () { - return this._signal; - }, - enumerable: false, - configurable: true - }); + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + get signal() { + return this._signal; + } /** * Signal that any operations passed this controller's associated abort signal * to cancel any remaining work and throw an `AbortError`. */ - AbortController.prototype.abort = function () { + abort() { abortSignal(this._signal); - }; + } /** * Creates a new AbortSignal instance that will abort after the provided ms. * @param ms - Elapsed time in milliseconds to trigger an abort. */ - AbortController.timeout = function (ms) { - var signal = new AbortSignal(); - var timer = setTimeout(abortSignal, ms, signal); + static timeout(ms) { + const signal = new AbortSignal(); + const timer = setTimeout(abortSignal, ms, signal); // Prevent the active Timer from keeping the Node.js event loop active. if (typeof timer.unref === "function") { timer.unref(); } return signal; - }; - return AbortController; -}()); + } +} exports.AbortController = AbortController; exports.AbortError = AbortError; @@ -9894,333 +9874,6 @@ exports.AbortSignal = AbortSignal; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 9268: -/***/ ((module) => { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), - -/***/ 2356: -/***/ (() => { - -"use strict"; - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -if (typeof Symbol === undefined || !Symbol.asyncIterator) { - Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); -} -//# sourceMappingURL=index.js.map - /***/ }), /***/ 9645: @@ -17483,6 +17136,689 @@ exports["default"] = _default; Object.defineProperty(exports, "__esModule", ({ value: true })); var logger$1 = __nccwpck_require__(3233); +var abortController = __nccwpck_require__(2557); +var coreUtil = __nccwpck_require__(1333); + +// Copyright (c) Microsoft Corporation. +/** + * The `@azure/logger` configuration for this package. + * @internal + */ +const logger = logger$1.createClientLogger("core-lro"); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The default time interval to wait before sending the next polling request. + */ +const POLL_INTERVAL_IN_MS = 2000; +/** + * The closed set of terminal states. + */ +const terminalStates = ["succeeded", "canceled", "failed"]; + +// Copyright (c) Microsoft Corporation. +/** + * Deserializes the state + */ +function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; + } + catch (e) { + throw new Error(`Unable to deserialize input state: ${serializedState}`); + } +} +function setStateError(inputs) { + const { state, stateProxy, isOperationError } = inputs; + return (error) => { + if (isOperationError(error)) { + stateProxy.setError(state, error); + stateProxy.setFailed(state); + } + throw error; + }; +} +function processOperationStatus(result) { + const { state, stateProxy, status, isDone, processResult, response, setErrorAsResult } = result; + switch (status) { + case "succeeded": { + stateProxy.setSucceeded(state); + break; + } + case "failed": { + stateProxy.setError(state, new Error(`The long-running operation has failed`)); + stateProxy.setFailed(state); + break; + } + case "canceled": { + stateProxy.setCanceled(state); + break; + } + } + if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || + (isDone === undefined && + ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) { + stateProxy.setResult(state, buildResult({ + response, + state, + processResult, + })); + } +} +function buildResult(inputs) { + const { processResult, response, state } = inputs; + return processResult ? processResult(response, state) : response; +} +/** + * Initiates the long-running operation. + */ +async function initOperation(inputs) { + const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs; + const { operationLocation, resourceLocation, metadata, response } = await init(); + if (operationLocation) + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); + const config = { + metadata, + operationLocation, + resourceLocation, + }; + logger.verbose(`LRO: Operation description:`, config); + const state = stateProxy.initState(config); + const status = getOperationStatus({ response, state, operationLocation }); + processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult }); + return state; +} +async function pollOperationHelper(inputs) { + const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs; + const response = await poll(operationLocation, options).catch(setStateError({ + state, + stateProxy, + isOperationError, + })); + const status = getOperationStatus(response, state); + logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); + if (status === "succeeded") { + const resourceLocation = getResourceLocation(response, state); + if (resourceLocation !== undefined) { + return { + response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })), + status, + }; + } + } + return { response, status }; +} +/** Polls the long-running operation. */ +async function pollOperation(inputs) { + const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, updateState, setDelay, isDone, setErrorAsResult, } = inputs; + const { operationLocation } = state.config; + if (operationLocation !== undefined) { + const { response, status } = await pollOperationHelper({ + poll, + getOperationStatus, + state, + stateProxy, + operationLocation, + getResourceLocation, + isOperationError, + options, + }); + processOperationStatus({ + status, + response, + state, + stateProxy, + isDone, + processResult, + setErrorAsResult, + }); + if (!terminalStates.includes(status)) { + const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); + if (intervalInMs) + setDelay(intervalInMs); + const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state); + if (location !== undefined) { + const isUpdated = operationLocation !== location; + state.config.operationLocation = location; + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated); + } + else + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); + } + updateState === null || updateState === void 0 ? void 0 : updateState(state, response); + } +} + +// Copyright (c) Microsoft Corporation. +function getOperationLocationPollingUrl(inputs) { + const { azureAsyncOperation, operationLocation } = inputs; + return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; +} +function getLocationHeader(rawResponse) { + return rawResponse.headers["location"]; +} +function getOperationLocationHeader(rawResponse) { + return rawResponse.headers["operation-location"]; +} +function getAzureAsyncOperationHeader(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; +} +function findResourceLocation(inputs) { + const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; + switch (requestMethod) { + case "PUT": { + return requestPath; + } + case "DELETE": { + return undefined; + } + default: { + switch (resourceLocationConfig) { + case "azure-async-operation": { + return undefined; + } + case "original-uri": { + return requestPath; + } + case "location": + default: { + return location; + } + } + } + } +} +function inferLroMode(inputs) { + const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs; + const operationLocation = getOperationLocationHeader(rawResponse); + const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse); + const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation }); + const location = getLocationHeader(rawResponse); + const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase(); + if (pollingUrl !== undefined) { + return { + mode: "OperationLocation", + operationLocation: pollingUrl, + resourceLocation: findResourceLocation({ + requestMethod: normalizedRequestMethod, + location, + requestPath, + resourceLocationConfig, + }), + }; + } + else if (location !== undefined) { + return { + mode: "ResourceLocation", + operationLocation: location, + }; + } + else if (normalizedRequestMethod === "PUT" && requestPath) { + return { + mode: "Body", + operationLocation: requestPath, + }; + } + else { + return undefined; + } +} +function transformStatus(inputs) { + const { status, statusCode } = inputs; + if (typeof status !== "string" && status !== undefined) { + throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`); + } + switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) { + case undefined: + return toOperationStatus(statusCode); + case "succeeded": + return "succeeded"; + case "failed": + return "failed"; + case "running": + case "accepted": + case "started": + case "canceling": + case "cancelling": + return "running"; + case "canceled": + case "cancelled": + return "canceled"; + default: { + logger.verbose(`LRO: unrecognized operation status: ${status}`); + return status; + } + } +} +function getStatus(rawResponse) { + var _a; + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + return transformStatus({ status, statusCode: rawResponse.statusCode }); +} +function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return transformStatus({ status, statusCode: rawResponse.statusCode }); +} +function toOperationStatus(statusCode) { + if (statusCode === 202) { + return "running"; + } + else if (statusCode < 300) { + return "succeeded"; + } + else { + return "failed"; + } +} +function parseRetryAfter({ rawResponse }) { + const retryAfter = rawResponse.headers["retry-after"]; + if (retryAfter !== undefined) { + // Retry-After header value is either in HTTP date format, or in seconds + const retryAfterInSeconds = parseInt(retryAfter); + return isNaN(retryAfterInSeconds) + ? calculatePollingIntervalFromDate(new Date(retryAfter)) + : retryAfterInSeconds * 1000; + } + return undefined; +} +function calculatePollingIntervalFromDate(retryAfterDate) { + const timeNow = Math.floor(new Date().getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return undefined; +} +function getStatusFromInitialResponse(inputs) { + const { response, state, operationLocation } = inputs; + function helper() { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case undefined: + return toOperationStatus(response.rawResponse.statusCode); + case "Body": + return getOperationStatus(response, state); + default: + return "running"; + } + } + const status = helper(); + return status === "running" && operationLocation === undefined ? "succeeded" : status; +} +/** + * Initiates the long-running operation. + */ +async function initHttpOperation(inputs) { + const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs; + return initOperation({ + init: async () => { + const response = await lro.sendInitialRequest(); + const config = inferLroMode({ + rawResponse: response.rawResponse, + requestPath: lro.requestPath, + requestMethod: lro.requestMethod, + resourceLocationConfig, + }); + return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); + }, + stateProxy, + processResult: processResult + ? ({ flatResponse }, state) => processResult(flatResponse, state) + : ({ flatResponse }) => flatResponse, + getOperationStatus: getStatusFromInitialResponse, + setErrorAsResult, + }); +} +function getOperationLocation({ rawResponse }, state) { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case "OperationLocation": { + return getOperationLocationPollingUrl({ + operationLocation: getOperationLocationHeader(rawResponse), + azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse), + }); + } + case "ResourceLocation": { + return getLocationHeader(rawResponse); + } + case "Body": + default: { + return undefined; + } + } +} +function getOperationStatus({ rawResponse }, state) { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case "OperationLocation": { + return getStatus(rawResponse); + } + case "ResourceLocation": { + return toOperationStatus(rawResponse.statusCode); + } + case "Body": { + return getProvisioningState(rawResponse); + } + default: + throw new Error(`Internal error: Unexpected operation mode: ${mode}`); + } +} +function getResourceLocation({ flatResponse }, state) { + if (typeof flatResponse === "object") { + const resourceLocation = flatResponse.resourceLocation; + if (resourceLocation !== undefined) { + state.config.resourceLocation = resourceLocation; + } + } + return state.config.resourceLocation; +} +function isOperationError(e) { + return e.name === "RestError"; +} +/** Polls the long-running operation. */ +async function pollHttpOperation(inputs) { + const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs; + return pollOperation({ + state, + stateProxy, + setDelay, + processResult: processResult + ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState) + : ({ flatResponse }) => flatResponse, + updateState, + getPollingInterval: parseRetryAfter, + getOperationLocation, + getOperationStatus, + isOperationError, + getResourceLocation, + options, + /** + * The expansion here is intentional because `lro` could be an object that + * references an inner this, so we need to preserve a reference to it. + */ + poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions), + setErrorAsResult, + }); +} + +// Copyright (c) Microsoft Corporation. +const createStateProxy$1 = () => ({ + /** + * The state at this point is created to be of type OperationState. + * It will be updated later to be of type TState when the + * customer-provided callback, `updateState`, is called during polling. + */ + initState: (config) => ({ status: "running", config }), + setCanceled: (state) => (state.status = "canceled"), + setError: (state, error) => (state.error = error), + setResult: (state, result) => (state.result = result), + setRunning: (state) => (state.status = "running"), + setSucceeded: (state) => (state.status = "succeeded"), + setFailed: (state) => (state.status = "failed"), + getError: (state) => state.error, + getResult: (state) => state.result, + isCanceled: (state) => state.status === "canceled", + isFailed: (state) => state.status === "failed", + isRunning: (state) => state.status === "running", + isSucceeded: (state) => state.status === "succeeded", +}); +/** + * Returns a poller factory. + */ +function buildCreatePoller(inputs) { + const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, resolveOnUnsuccessful, } = inputs; + return async ({ init, poll }, options) => { + const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {}; + const stateProxy = createStateProxy$1(); + const withOperationLocation = withOperationLocationCallback + ? (() => { + let called = false; + return (operationLocation, isUpdated) => { + if (isUpdated) + withOperationLocationCallback(operationLocation); + else if (!called) + withOperationLocationCallback(operationLocation); + called = true; + }; + })() + : undefined; + const state = restoreFrom + ? deserializeState(restoreFrom) + : await initOperation({ + init, + stateProxy, + processResult, + getOperationStatus: getStatusFromInitialResponse, + withOperationLocation, + setErrorAsResult: !resolveOnUnsuccessful, + }); + let resultPromise; + const abortController$1 = new abortController.AbortController(); + const handlers = new Map(); + const handleProgressEvents = async () => handlers.forEach((h) => h(state)); + const cancelErrMsg = "Operation was canceled"; + let currentPollIntervalInMs = intervalInMs; + const poller = { + getOperationState: () => state, + getResult: () => state.result, + isDone: () => ["succeeded", "failed", "canceled"].includes(state.status), + isStopped: () => resultPromise === undefined, + stopPolling: () => { + abortController$1.abort(); + }, + toString: () => JSON.stringify({ + state, + }), + onProgress: (callback) => { + const s = Symbol(); + handlers.set(s, callback); + return () => handlers.delete(s); + }, + pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => { + const { abortSignal: inputAbortSignal } = pollOptions || {}; + const { signal: abortSignal } = inputAbortSignal + ? new abortController.AbortController([inputAbortSignal, abortController$1.signal]) + : abortController$1; + if (!poller.isDone()) { + await poller.poll({ abortSignal }); + while (!poller.isDone()) { + await coreUtil.delay(currentPollIntervalInMs, { abortSignal }); + await poller.poll({ abortSignal }); + } + } + if (resolveOnUnsuccessful) { + return poller.getResult(); + } + else { + switch (state.status) { + case "succeeded": + return poller.getResult(); + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; + case "notStarted": + case "running": + throw new Error(`Polling completed without succeeding or failing`); + } + } + })().finally(() => { + resultPromise = undefined; + }))), + async poll(pollOptions) { + if (resolveOnUnsuccessful) { + if (poller.isDone()) + return; + } + else { + switch (state.status) { + case "succeeded": + return; + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; + } + } + await pollOperation({ + poll, + state, + stateProxy, + getOperationLocation, + isOperationError, + withOperationLocation, + getPollingInterval, + getOperationStatus: getStatusFromPollResponse, + getResourceLocation, + processResult, + updateState, + options: pollOptions, + setDelay: (pollIntervalInMs) => { + currentPollIntervalInMs = pollIntervalInMs; + }, + setErrorAsResult: !resolveOnUnsuccessful, + }); + await handleProgressEvents(); + if (!resolveOnUnsuccessful) { + switch (state.status) { + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; + } + } + }, + }; + return poller; + }; +} + +// Copyright (c) Microsoft Corporation. +/** + * Creates a poller that can be used to poll a long-running operation. + * @param lro - Description of the long-running operation + * @param options - options to configure the poller + * @returns an initialized poller + */ +async function createHttpPoller(lro, options) { + const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {}; + return buildCreatePoller({ + getStatusFromInitialResponse, + getStatusFromPollResponse: getOperationStatus, + isOperationError, + getOperationLocation, + getResourceLocation, + getPollingInterval: parseRetryAfter, + resolveOnUnsuccessful, + })({ + init: async () => { + const response = await lro.sendInitialRequest(); + const config = inferLroMode({ + rawResponse: response.rawResponse, + requestPath: lro.requestPath, + requestMethod: lro.requestMethod, + resourceLocationConfig, + }); + return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); + }, + poll: lro.sendPollRequest, + }, { + intervalInMs, + withOperationLocation, + restoreFrom, + updateState, + processResult: processResult + ? ({ flatResponse }, state) => processResult(flatResponse, state) + : ({ flatResponse }) => flatResponse, + }); +} + +// Copyright (c) Microsoft Corporation. +const createStateProxy = () => ({ + initState: (config) => ({ config, isStarted: true }), + setCanceled: (state) => (state.isCancelled = true), + setError: (state, error) => (state.error = error), + setResult: (state, result) => (state.result = result), + setRunning: (state) => (state.isStarted = true), + setSucceeded: (state) => (state.isCompleted = true), + setFailed: () => { + /** empty body */ + }, + getError: (state) => state.error, + getResult: (state) => state.result, + isCanceled: (state) => !!state.isCancelled, + isFailed: (state) => !!state.error, + isRunning: (state) => !!state.isStarted, + isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error), +}); +class GenericPollOperation { + constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.setErrorAsResult = setErrorAsResult; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + async update(options) { + var _a; + const stateProxy = createStateProxy(); + if (!this.state.isStarted) { + this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({ + lro: this.lro, + stateProxy, + resourceLocationConfig: this.lroResourceLocationConfig, + processResult: this.processResult, + setErrorAsResult: this.setErrorAsResult, + }))); + } + const updateState = this.updateState; + const isDone = this.isDone; + if (!this.state.isCompleted && this.state.error === undefined) { + await pollHttpOperation({ + lro: this.lro, + state: this.state, + stateProxy, + processResult: this.processResult, + updateState: updateState + ? (state, { rawResponse }) => updateState(state, rawResponse) + : undefined, + isDone: isDone + ? ({ flatResponse }, state) => isDone(flatResponse, state) + : undefined, + options, + setDelay: (intervalInMs) => { + this.pollerConfig.intervalInMs = intervalInMs; + }, + setErrorAsResult: this.setErrorAsResult, + }); + } + (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state); + return this; + } + async cancel() { + logger.error("`cancelOperation` is deprecated because it wasn't implemented"); + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state, + }); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -17498,8 +17834,8 @@ class PollerStoppedError extends Error { } } /** - * When a poller is cancelled through the `cancelOperation` method, - * the poller will be rejected with an instance of the PollerCancelledError. + * When the operation is cancelled, the poller will be rejected with an instance + * of the PollerCancelledError. */ class PollerCancelledError extends Error { constructor(message) { @@ -17637,6 +17973,8 @@ class Poller { * @param operation - Must contain the basic properties of `PollOperation`. */ constructor(operation) { + /** controls whether to throw an error if the operation failed or was canceled. */ + this.resolveOnUnsuccessful = false; this.stopped = true; this.pollProgressCallbacks = []; this.operation = operation; @@ -17655,12 +17993,12 @@ class Poller { * Starts a loop that will break only if the poller is done * or if the poller is stopped. */ - async startPolling() { + async startPolling(pollOptions = {}) { if (this.stopped) { this.stopped = false; } while (!this.isStopped() && !this.isDone()) { - await this.poll(); + await this.poll(pollOptions); await this.delay(); } } @@ -17673,29 +18011,13 @@ class Poller { * @param options - Optional properties passed to the operation's update method. */ async pollOnce(options = {}) { - try { - if (!this.isDone()) { - this.operation = await this.operation.update({ - abortSignal: options.abortSignal, - fireProgress: this.fireProgress.bind(this), - }); - if (this.isDone() && this.resolve) { - // If the poller has finished polling, this means we now have a result. - // However, it can be the case that TResult is instantiated to void, so - // we are not expecting a result anyway. To assert that we might not - // have a result eventually after finishing polling, we cast the result - // to TResult. - this.resolve(this.operation.state.result); - } - } - } - catch (e) { - this.operation.state.error = e; - if (this.reject) { - this.reject(e); - } - throw e; + if (!this.isDone()) { + this.operation = await this.operation.update({ + abortSignal: options.abortSignal, + fireProgress: this.fireProgress.bind(this), + }); } + this.processUpdatedState(); } /** * fireProgress calls the functions passed in via onProgress the method of the poller. @@ -17711,14 +18033,10 @@ class Poller { } } /** - * Invokes the underlying operation's cancel method, and rejects the - * pollUntilDone promise. + * Invokes the underlying operation's cancel method. */ async cancelOnce(options = {}) { this.operation = await this.operation.cancel(options); - if (this.reject) { - this.reject(new PollerCancelledError("Poller cancelled")); - } } /** * Returns a promise that will resolve once a single polling request finishes. @@ -17738,13 +18056,41 @@ class Poller { } return this.pollOncePromise; } + processUpdatedState() { + if (this.operation.state.error) { + this.stopped = true; + if (!this.resolveOnUnsuccessful) { + this.reject(this.operation.state.error); + throw this.operation.state.error; + } + } + if (this.operation.state.isCancelled) { + this.stopped = true; + if (!this.resolveOnUnsuccessful) { + const error = new PollerCancelledError("Operation was canceled"); + this.reject(error); + throw error; + } + } + if (this.isDone() && this.resolve) { + // If the poller has finished polling, this means we now have a result. + // However, it can be the case that TResult is instantiated to void, so + // we are not expecting a result anyway. To assert that we might not + // have a result eventually after finishing polling, we cast the result + // to TResult. + this.resolve(this.getResult()); + } + } /** * Returns a promise that will resolve once the underlying operation is completed. */ - async pollUntilDone() { + async pollUntilDone(pollOptions = {}) { if (this.stopped) { - this.startPolling().catch(this.reject); + this.startPolling(pollOptions).catch(this.reject); } + // This is needed because the state could have been updated by + // `cancelOperation`, e.g. the operation is canceled or an error occurred. + this.processUpdatedState(); return this.promise; } /** @@ -17793,9 +18139,6 @@ class Poller { * @param options - Optional properties passed to the operation's update method. */ cancelOperation(options = {}) { - if (!this.stopped) { - this.stopped = true; - } if (!this.cancelPromise) { this.cancelPromise = this.cancelOnce(options); } @@ -17875,344 +18218,18 @@ class Poller { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Detects where the continuation token is and returns it. Notice that azure-asyncoperation - * must be checked first before the other location headers because there are scenarios - * where both azure-asyncoperation and location could be present in the same response but - * azure-asyncoperation should be the one to use for polling. - */ -function getPollingUrl(rawResponse, defaultPath) { - var _a, _b, _c; - return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getOperationLocation(rawResponse)) !== null && _b !== void 0 ? _b : getLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath); -} -function getLocation(rawResponse) { - return rawResponse.headers["location"]; -} -function getOperationLocation(rawResponse) { - return rawResponse.headers["operation-location"]; -} -function getAzureAsyncOperation(rawResponse) { - return rawResponse.headers["azure-asyncoperation"]; -} -function findResourceLocation(requestMethod, rawResponse, requestPath) { - switch (requestMethod) { - case "PUT": { - return requestPath; - } - case "POST": - case "PATCH": { - return getLocation(rawResponse); - } - default: { - return undefined; - } - } -} -function inferLroMode(requestPath, requestMethod, rawResponse) { - if (getAzureAsyncOperation(rawResponse) !== undefined || - getOperationLocation(rawResponse) !== undefined) { - return { - mode: "Location", - resourceLocation: findResourceLocation(requestMethod, rawResponse, requestPath), - }; - } - else if (getLocation(rawResponse) !== undefined) { - return { - mode: "Location", - }; - } - else if (["PUT", "PATCH"].includes(requestMethod)) { - return { - mode: "Body", - }; - } - return {}; -} -class SimpleRestError extends Error { - constructor(message, statusCode) { - super(message); - this.name = "RestError"; - this.statusCode = statusCode; - Object.setPrototypeOf(this, SimpleRestError.prototype); - } -} -function isUnexpectedInitialResponse(rawResponse) { - const code = rawResponse.statusCode; - if (![203, 204, 202, 201, 200, 500].includes(code)) { - throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code); - } - return false; -} -function isUnexpectedPollingResponse(rawResponse) { - const code = rawResponse.statusCode; - if (![202, 201, 200, 500].includes(code)) { - throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); - } - return false; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -const successStates = ["succeeded"]; -const failureStates = ["failed", "canceled", "cancelled"]; - -// Copyright (c) Microsoft Corporation. -function getProvisioningState(rawResponse) { - var _a, _b; - const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; - return typeof state === "string" ? state.toLowerCase() : "succeeded"; -} -function isBodyPollingDone(rawResponse) { - const state = getProvisioningState(rawResponse); - if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { - throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); - } - return successStates.includes(state); -} -/** - * Creates a polling strategy based on BodyPolling which uses the provisioning state - * from the result to determine the current operation state - */ -function processBodyPollingOperationResult(response) { - return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) }); -} - -// Copyright (c) Microsoft Corporation. -/** - * The `@azure/logger` configuration for this package. - * @internal - */ -const logger = logger$1.createClientLogger("core-lro"); - -// Copyright (c) Microsoft Corporation. -function isPollingDone(rawResponse) { - var _a; - if (isUnexpectedPollingResponse(rawResponse) || rawResponse.statusCode === 202) { - return false; - } - const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const state = typeof status === "string" ? status.toLowerCase() : "succeeded"; - if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { - throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); - } - return successStates.includes(state); -} -/** - * Sends a request to the URI of the provisioned resource if needed. - */ -async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) { - switch (lroResourceLocationConfig) { - case "original-uri": - return lro.sendPollRequest(lro.requestPath); - case "azure-async-operation": - return undefined; - case "location": - default: - return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath); - } -} -function processLocationPollingOperationResult(lro, resourceLocation, lroResourceLocationConfig) { - return (response) => { - if (isPollingDone(response.rawResponse)) { - if (resourceLocation === undefined) { - return Object.assign(Object.assign({}, response), { done: true }); - } - else { - return Object.assign(Object.assign({}, response), { done: false, next: async () => { - const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig); - return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true }); - } }); - } - } - return Object.assign(Object.assign({}, response), { done: false }); - }; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -function processPassthroughOperationResult(response) { - return Object.assign(Object.assign({}, response), { done: true }); -} - -// Copyright (c) Microsoft Corporation. -/** - * creates a stepping function that maps an LRO state to another. - */ -function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) { - switch (config.mode) { - case "Location": { - return processLocationPollingOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig); - } - case "Body": { - return processBodyPollingOperationResult; - } - default: { - return processPassthroughOperationResult; - } - } -} -/** - * Creates a polling operation. - */ -function createPoll(lroPrimitives) { - return async (path, pollerConfig, getLroStatusFromResponse) => { - const response = await lroPrimitives.sendPollRequest(path); - const retryAfter = response.rawResponse.headers["retry-after"]; - if (retryAfter !== undefined) { - // Retry-After header value is either in HTTP date format, or in seconds - const retryAfterInSeconds = parseInt(retryAfter); - pollerConfig.intervalInMs = isNaN(retryAfterInSeconds) - ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) - : retryAfterInSeconds * 1000; - } - return getLroStatusFromResponse(response); - }; -} -function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { - const timeNow = Math.floor(new Date().getTime()); - const retryAfterTime = retryAfterDate.getTime(); - if (timeNow < retryAfterTime) { - return retryAfterTime - timeNow; - } - return defaultIntervalInMs; -} -/** - * Creates a callback to be used to initialize the polling operation state. - * @param state - of the polling operation - * @param operationSpec - of the LRO - * @param callback - callback to be called when the operation is done - * @returns callback that initializes the state of the polling operation - */ -function createInitializeState(state, requestPath, requestMethod) { - return (response) => { - if (isUnexpectedInitialResponse(response.rawResponse)) - ; - state.initialRawResponse = response.rawResponse; - state.isStarted = true; - state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath); - state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse); - /** short circuit polling if body polling is done in the initial request */ - if (state.config.mode === undefined || - (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) { - state.result = response.flatResponse; - state.isCompleted = true; - } - logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`); - return Boolean(state.isCompleted); - }; -} - -// Copyright (c) Microsoft Corporation. -class GenericPollOperation { - constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { - this.state = state; - this.lro = lro; - this.lroResourceLocationConfig = lroResourceLocationConfig; - this.processResult = processResult; - this.updateState = updateState; - this.isDone = isDone; - } - setPollerConfig(pollerConfig) { - this.pollerConfig = pollerConfig; - } - /** - * General update function for LROPoller, the general process is as follows - * 1. Check initial operation result to determine the strategy to use - * - Strategies: Location, Azure-AsyncOperation, Original Uri - * 2. Check if the operation result has a terminal state - * - Terminal state will be determined by each strategy - * 2.1 If it is terminal state Check if a final GET request is required, if so - * send final GET request and return result from operation. If no final GET - * is required, just return the result from operation. - * - Determining what to call for final request is responsibility of each strategy - * 2.2 If it is not terminal state, call the polling operation and go to step 1 - * - Determining what to call for polling is responsibility of each strategy - * - Strategies will always use the latest URI for polling if provided otherwise - * the last known one - */ - async update(options) { - var _a, _b, _c; - const state = this.state; - let lastResponse = undefined; - if (!state.isStarted) { - const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod); - lastResponse = await this.lro.sendInitialRequest(); - initializeState(lastResponse); - } - if (!state.isCompleted) { - if (!this.poll || !this.getLroStatusFromResponse) { - if (!state.config) { - throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed."); - } - const isDone = this.isDone; - this.getLroStatusFromResponse = isDone - ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) - : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig); - this.poll = createPoll(this.lro); - } - if (!state.pollingURL) { - throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed."); - } - const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse); - logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`); - if (currentState.done) { - state.result = this.processResult - ? this.processResult(currentState.flatResponse, state) - : currentState.flatResponse; - state.isCompleted = true; - } - else { - this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; - state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL); - } - lastResponse = currentState; - } - logger.verbose(`LRO: current state: ${JSON.stringify(state)}`); - if (lastResponse) { - (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); - } - else { - logger.error(`LRO: no response was received`); - } - (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); - return this; - } - async cancel() { - this.state.isCancelled = true; - return this; - } - /** - * Serializes the Poller operation. - */ - toString() { - return JSON.stringify({ - state: this.state, - }); - } -} - -// Copyright (c) Microsoft Corporation. -function deserializeState(serializedState) { - try { - return JSON.parse(serializedState).state; - } - catch (e) { - throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); - } -} /** * The LRO Engine, a class that performs polling. */ class LroEngine extends Poller { constructor(lro, options) { - const { intervalInMs = 2000, resumeFrom } = options || {}; + const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {}; const state = resumeFrom ? deserializeState(resumeFrom) : {}; - const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone); + const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone); super(operation); + this.resolveOnUnsuccessful = resolveOnUnsuccessful; this.config = { intervalInMs: intervalInMs }; operation.setPollerConfig(this.config); } @@ -18228,6 +18245,7 @@ exports.LroEngine = LroEngine; exports.Poller = Poller; exports.PollerCancelledError = PollerCancelledError; exports.PollerStoppedError = PollerStoppedError; +exports.createHttpPoller = createHttpPoller; //# sourceMappingURL=index.js.map @@ -18241,7 +18259,6 @@ exports.PollerStoppedError = PollerStoppedError; Object.defineProperty(exports, "__esModule", ({ value: true })); -__nccwpck_require__(2356); var tslib = __nccwpck_require__(6429); // Copyright (c) Microsoft Corporation. @@ -18263,47 +18280,78 @@ function getPagedAsyncIterator(pagedResult) { return this; }, byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => { - return getPageAsyncIterator(pagedResult, settings === null || settings === void 0 ? void 0 : settings.maxPageSize); + const { continuationToken, maxPageSize } = settings !== null && settings !== void 0 ? settings : {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + maxPageSize, + }); }), }; } -function getItemAsyncIterator(pagedResult, maxPageSize) { +function getItemAsyncIterator(pagedResult) { return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() { - var e_1, _a; - const pages = getPageAsyncIterator(pagedResult, maxPageSize); + var e_1, _a, e_2, _b; + const pages = getPageAsyncIterator(pagedResult); const firstVal = yield tslib.__await(pages.next()); // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is if (!Array.isArray(firstVal.value)) { - yield yield tslib.__await(firstVal.value); - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(firstVal.value)))); + try { + for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { + const page = pages_1_1.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(page)))); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); + } + finally { if (e_1) throw e_1.error; } + } + } + else { + yield yield tslib.__await(firstVal.value); + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); + } } else { yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value))); try { - for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { - const page = pages_1_1.value; + for (var pages_2 = tslib.__asyncValues(pages), pages_2_1; pages_2_1 = yield tslib.__await(pages_2.next()), !pages_2_1.done;) { + const page = pages_2_1.value; // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, // it must be the case that `TPage = TElement[]` yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page))); } } - catch (e_1_1) { e_1 = { error: e_1_1 }; } + catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { - if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); + if (pages_2_1 && !pages_2_1.done && (_b = pages_2.return)) yield tslib.__await(_b.call(pages_2)); } - finally { if (e_1) throw e_1.error; } + finally { if (e_2) throw e_2.error; } } } }); } -function getPageAsyncIterator(pagedResult, maxPageSize) { +function getPageAsyncIterator(pagedResult, options = {}) { return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() { - let response = yield tslib.__await(pagedResult.getPage(pagedResult.firstPageLink, maxPageSize)); + const { pageLink, maxPageSize } = options; + let response = yield tslib.__await(pagedResult.getPage(pageLink !== null && pageLink !== void 0 ? pageLink : pagedResult.firstPageLink, maxPageSize)); + if (!response) { + return yield tslib.__await(void 0); + } yield yield tslib.__await(response.page); while (response.nextPageLink) { response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); + if (!response) { + return yield tslib.__await(void 0); + } yield yield tslib.__await(response.page); } }); @@ -18318,7 +18366,7 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator; /***/ 6429: /***/ ((module) => { -/*! ***************************************************************************** +/****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -18338,6 +18386,10 @@ var __assign; var __rest; var __decorate; var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -18356,6 +18408,7 @@ var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; +var __classPrivateFieldIn; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; @@ -18424,6 +18477,51 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.push(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.push(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; @@ -18444,7 +18542,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (_) try { + while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -18472,7 +18570,11 @@ var __createBinding; __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -18552,7 +18654,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -18599,11 +18701,20 @@ var __createBinding; return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -18623,6 +18734,7 @@ var __createBinding; exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); }); @@ -19105,14 +19217,16 @@ exports.randomUUID = randomUUID; Object.defineProperty(exports, "__esModule", ({ value: true })); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var util = _interopDefault(__nccwpck_require__(3837)); var os = __nccwpck_require__(2037); +var util = __nccwpck_require__(3837); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var util__default = /*#__PURE__*/_interopDefaultLegacy(util); // Copyright (c) Microsoft Corporation. function log(message, ...args) { - process.stderr.write(`${util.format(message, ...args)}${os.EOL}`); + process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); } // Copyright (c) Microsoft Corporation. @@ -19130,7 +19244,7 @@ const debugObj = Object.assign((namespace) => { enable, enabled, disable, - log + log, }); function enable(namespaces) { enabledString = namespaces; @@ -19177,7 +19291,7 @@ function createDebugger(namespace) { destroy, log: debugObj.log, namespace, - extend + extend, }); function debug(...args) { if (!newDebugger.enabled) { @@ -19204,6 +19318,7 @@ function extend(namespace) { newDebugger.log = this.log; return newDebugger; } +var debug = debugObj; // Copyright (c) Microsoft Corporation. const registeredLoggers = new Set(); @@ -19214,9 +19329,9 @@ let azureLogLevel; * By default, logs are sent to stderr. * Override the `log` method to redirect logs to another location. */ -const AzureLogger = debugObj("azure"); +const AzureLogger = debug("azure"); AzureLogger.log = (...args) => { - debugObj.log(...args); + debug.log(...args); }; const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; if (logLevelFromEnv) { @@ -19229,7 +19344,7 @@ if (logLevelFromEnv) { } } /** - * Immediately enables logging at the specified log level. + * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. * @param level - The log level to enable for logging. * Options from most verbose to least verbose are: * - verbose @@ -19248,7 +19363,7 @@ function setLogLevel(level) { enabledNamespaces.push(logger.namespace); } } - debugObj.enable(enabledNamespaces.join(",")); + debug.enable(enabledNamespaces.join(",")); } /** * Retrieves the currently specified log level. @@ -19260,7 +19375,7 @@ const levelMap = { verbose: 400, info: 300, warning: 200, - error: 100 + error: 100, }; /** * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. @@ -19274,7 +19389,7 @@ function createClientLogger(namespace) { error: createLogger(clientRootLogger, "error"), warning: createLogger(clientRootLogger, "warning"), info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") + verbose: createLogger(clientRootLogger, "verbose"), }; } function patchLogMethod(parent, child) { @@ -19284,23 +19399,18 @@ function patchLogMethod(parent, child) { } function createLogger(parent, level) { const logger = Object.assign(parent.extend(level), { - level + level, }); patchLogMethod(parent, logger); if (shouldEnable(logger)) { - const enabledNamespaces = debugObj.disable(); - debugObj.enable(enabledNamespaces + "," + logger.namespace); + const enabledNamespaces = debug.disable(); + debug.enable(enabledNamespaces + "," + logger.namespace); } registeredLoggers.add(logger); return logger; } function shouldEnable(logger) { - if (azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]) { - return true; - } - else { - return false; - } + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); } function isAzureLogLevel(logLevel) { return AZURE_LOG_LEVELS.includes(logLevel); @@ -44441,7 +44551,7 @@ exports.newPipeline = newPipeline; /***/ 679: /***/ ((module) => { -/*! ***************************************************************************** +/****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -44461,6 +44571,10 @@ var __assign; var __rest; var __decorate; var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -44479,6 +44593,7 @@ var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; +var __classPrivateFieldIn; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; @@ -44547,6 +44662,51 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.push(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.push(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; @@ -44567,7 +44727,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (_) try { + while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -44595,7 +44755,11 @@ var __createBinding; __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -44675,7 +44839,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -44722,11 +44886,20 @@ var __createBinding; return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -44746,6 +44919,7 @@ var __createBinding; exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); }); @@ -46974,7 +47148,7 @@ function validate(octokit, options) { /***/ }), /***/ 7171: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46993,46 +47167,40 @@ function validate(octokit, options) { * See the License for the specific language governing permissions and * limitations under the License. */ -var __spreadArray = (this && this.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; -var NoopContextManager_1 = __nccwpck_require__(4118); -var global_utils_1 = __nccwpck_require__(5135); -var diag_1 = __nccwpck_require__(1877); -var API_NAME = 'context'; -var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); +const NoopContextManager_1 = __nccwpck_require__(4118); +const global_utils_1 = __nccwpck_require__(5135); +const diag_1 = __nccwpck_require__(1877); +const API_NAME = 'context'; +const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** * Singleton object which represents the entry point to the OpenTelemetry Context API */ -var ContextAPI = /** @class */ (function () { +class ContextAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ - function ContextAPI() { - } + constructor() { } /** Get the singleton instance of the Context API */ - ContextAPI.getInstance = function () { + static getInstance() { if (!this._instance) { this._instance = new ContextAPI(); } return this._instance; - }; + } /** * Set the current context manager. * * @returns true if the context manager was successfully registered, else false */ - ContextAPI.prototype.setGlobalContextManager = function (contextManager) { - return global_utils_1.registerGlobal(API_NAME, contextManager, diag_1.DiagAPI.instance()); - }; + setGlobalContextManager(contextManager) { + return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); + } /** * Get the currently active context */ - ContextAPI.prototype.active = function () { + active() { return this._getContextManager().active(); - }; + } /** * Execute a function with an active context * @@ -47041,33 +47209,27 @@ var ContextAPI = /** @class */ (function () { * @param thisArg optional receiver to be used for calling fn * @param args optional arguments forwarded to fn */ - ContextAPI.prototype.with = function (context, fn, thisArg) { - var _a; - var args = []; - for (var _i = 3; _i < arguments.length; _i++) { - args[_i - 3] = arguments[_i]; - } - return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], args)); - }; + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); + } /** * Bind a context to a target function or event emitter * * @param context context to bind to the event emitter or function. Defaults to the currently active context * @param target function or event emitter to bind */ - ContextAPI.prototype.bind = function (context, target) { + bind(context, target) { return this._getContextManager().bind(context, target); - }; - ContextAPI.prototype._getContextManager = function () { - return global_utils_1.getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER; - }; + } + _getContextManager() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; + } /** Disable and remove the global context manager */ - ContextAPI.prototype.disable = function () { + disable() { this._getContextManager().disable(); - global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); - }; - return ContextAPI; -}()); + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } +} exports.ContextAPI = ContextAPI; //# sourceMappingURL=context.js.map @@ -47095,62 +47257,63 @@ exports.ContextAPI = ContextAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; -var ComponentLogger_1 = __nccwpck_require__(7978); -var logLevelLogger_1 = __nccwpck_require__(9639); -var types_1 = __nccwpck_require__(8077); -var global_utils_1 = __nccwpck_require__(5135); -var API_NAME = 'diag'; +const ComponentLogger_1 = __nccwpck_require__(7978); +const logLevelLogger_1 = __nccwpck_require__(9639); +const types_1 = __nccwpck_require__(8077); +const global_utils_1 = __nccwpck_require__(5135); +const API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal * diagnostic API */ -var DiagAPI = /** @class */ (function () { +class DiagAPI { /** * Private internal constructor * @private */ - function DiagAPI() { + constructor() { function _logProxy(funcName) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var logger = global_utils_1.getGlobal('diag'); + return function (...args) { + const logger = (0, global_utils_1.getGlobal)('diag'); // shortcut if logger not set if (!logger) return; - return logger[funcName].apply(logger, args); + return logger[funcName](...args); }; } // Using self local variable for minification purposes as 'this' cannot be minified - var self = this; + const self = this; // DiagAPI specific functions - self.setLogger = function (logger, logLevel) { - var _a, _b; - if (logLevel === void 0) { logLevel = types_1.DiagLogLevel.INFO; } + const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { + var _a, _b, _c; if (logger === self) { // There isn't much we can do here. // Logging to the console might break the user application. // Try to log to self. If a logger was previously registered it will receive the log. - var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); return false; } - var oldLogger = global_utils_1.getGlobal('diag'); - var newLogger = logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger); + if (typeof optionsOrLogLevel === 'number') { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel, + }; + } + const oldLogger = (0, global_utils_1.getGlobal)('diag'); + const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); // There already is an logger registered. We'll let it know before overwriting it. - if (oldLogger) { - var stack = (_b = new Error().stack) !== null && _b !== void 0 ? _b : ''; - oldLogger.warn("Current logger will be overwritten from " + stack); - newLogger.warn("Current logger will overwrite one already registered from " + stack); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); } - return global_utils_1.registerGlobal('diag', newLogger, self, true); + return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); }; - self.disable = function () { - global_utils_1.unregisterGlobal(API_NAME, self); + self.setLogger = setLogger; + self.disable = () => { + (0, global_utils_1.unregisterGlobal)(API_NAME, self); }; - self.createComponentLogger = function (options) { + self.createComponentLogger = (options) => { return new ComponentLogger_1.DiagComponentLogger(options); }; self.verbose = _logProxy('verbose'); @@ -47160,19 +47323,86 @@ var DiagAPI = /** @class */ (function () { self.error = _logProxy('error'); } /** Get the singleton instance of the DiagAPI API */ - DiagAPI.instance = function () { + static instance() { if (!this._instance) { this._instance = new DiagAPI(); } return this._instance; - }; - return DiagAPI; -}()); + } +} exports.DiagAPI = DiagAPI; //# sourceMappingURL=diag.js.map /***/ }), +/***/ 7696: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MetricsAPI = void 0; +const NoopMeterProvider_1 = __nccwpck_require__(2647); +const global_utils_1 = __nccwpck_require__(5135); +const diag_1 = __nccwpck_require__(1877); +const API_NAME = 'metrics'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + /** Remove the global meter provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } +} +exports.MetricsAPI = MetricsAPI; +//# sourceMappingURL=metrics.js.map + +/***/ }), + /***/ 9909: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -47195,40 +47425,41 @@ exports.DiagAPI = DiagAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; -var global_utils_1 = __nccwpck_require__(5135); -var NoopTextMapPropagator_1 = __nccwpck_require__(2368); -var TextMapPropagator_1 = __nccwpck_require__(865); -var context_helpers_1 = __nccwpck_require__(7682); -var utils_1 = __nccwpck_require__(8136); -var diag_1 = __nccwpck_require__(1877); -var API_NAME = 'propagation'; -var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); +const global_utils_1 = __nccwpck_require__(5135); +const NoopTextMapPropagator_1 = __nccwpck_require__(2368); +const TextMapPropagator_1 = __nccwpck_require__(865); +const context_helpers_1 = __nccwpck_require__(7682); +const utils_1 = __nccwpck_require__(8136); +const diag_1 = __nccwpck_require__(1877); +const API_NAME = 'propagation'; +const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** * Singleton object which represents the entry point to the OpenTelemetry Propagation API */ -var PropagationAPI = /** @class */ (function () { +class PropagationAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ - function PropagationAPI() { + constructor() { this.createBaggage = utils_1.createBaggage; this.getBaggage = context_helpers_1.getBaggage; + this.getActiveBaggage = context_helpers_1.getActiveBaggage; this.setBaggage = context_helpers_1.setBaggage; this.deleteBaggage = context_helpers_1.deleteBaggage; } /** Get the singleton instance of the Propagator API */ - PropagationAPI.getInstance = function () { + static getInstance() { if (!this._instance) { this._instance = new PropagationAPI(); } return this._instance; - }; + } /** * Set the current propagator. * * @returns true if the propagator was successfully registered, else false */ - PropagationAPI.prototype.setGlobalPropagator = function (propagator) { - return global_utils_1.registerGlobal(API_NAME, propagator, diag_1.DiagAPI.instance()); - }; + setGlobalPropagator(propagator) { + return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); + } /** * Inject context into a carrier to be propagated inter-process * @@ -47236,10 +47467,9 @@ var PropagationAPI = /** @class */ (function () { * @param carrier carrier to inject context into * @param setter Function used to set values on the carrier */ - PropagationAPI.prototype.inject = function (context, carrier, setter) { - if (setter === void 0) { setter = TextMapPropagator_1.defaultTextMapSetter; } + inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { return this._getGlobalPropagator().inject(context, carrier, setter); - }; + } /** * Extract context from a carrier * @@ -47247,25 +47477,23 @@ var PropagationAPI = /** @class */ (function () { * @param carrier Carrier to extract context from * @param getter Function used to extract keys from a carrier */ - PropagationAPI.prototype.extract = function (context, carrier, getter) { - if (getter === void 0) { getter = TextMapPropagator_1.defaultTextMapGetter; } + extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { return this._getGlobalPropagator().extract(context, carrier, getter); - }; + } /** * Return a list of all fields which may be used by the propagator. */ - PropagationAPI.prototype.fields = function () { + fields() { return this._getGlobalPropagator().fields(); - }; + } /** Remove the global propagator */ - PropagationAPI.prototype.disable = function () { - global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); - }; - PropagationAPI.prototype._getGlobalPropagator = function () { - return global_utils_1.getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; - }; - return PropagationAPI; -}()); + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + _getGlobalPropagator() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + } +} exports.PropagationAPI = PropagationAPI; //# sourceMappingURL=propagation.js.map @@ -47293,65 +47521,65 @@ exports.PropagationAPI = PropagationAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; -var global_utils_1 = __nccwpck_require__(5135); -var ProxyTracerProvider_1 = __nccwpck_require__(2285); -var spancontext_utils_1 = __nccwpck_require__(9745); -var context_utils_1 = __nccwpck_require__(3326); -var diag_1 = __nccwpck_require__(1877); -var API_NAME = 'trace'; +const global_utils_1 = __nccwpck_require__(5135); +const ProxyTracerProvider_1 = __nccwpck_require__(2285); +const spancontext_utils_1 = __nccwpck_require__(9745); +const context_utils_1 = __nccwpck_require__(3326); +const diag_1 = __nccwpck_require__(1877); +const API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API */ -var TraceAPI = /** @class */ (function () { +class TraceAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ - function TraceAPI() { + constructor() { this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; this.deleteSpan = context_utils_1.deleteSpan; this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; this.getSpanContext = context_utils_1.getSpanContext; this.setSpan = context_utils_1.setSpan; this.setSpanContext = context_utils_1.setSpanContext; } /** Get the singleton instance of the Trace API */ - TraceAPI.getInstance = function () { + static getInstance() { if (!this._instance) { this._instance = new TraceAPI(); } return this._instance; - }; + } /** * Set the current global tracer. * * @returns true if the tracer provider was successfully registered, else false */ - TraceAPI.prototype.setGlobalTracerProvider = function (provider) { - var success = global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + setGlobalTracerProvider(provider) { + const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); if (success) { this._proxyTracerProvider.setDelegate(provider); } return success; - }; + } /** * Returns the global tracer provider. */ - TraceAPI.prototype.getTracerProvider = function () { - return global_utils_1.getGlobal(API_NAME) || this._proxyTracerProvider; - }; + getTracerProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; + } /** * Returns a tracer from the global tracer provider. */ - TraceAPI.prototype.getTracer = function (name, version) { + getTracer(name, version) { return this.getTracerProvider().getTracer(name, version); - }; + } /** Remove the global tracer provider */ - TraceAPI.prototype.disable = function () { - global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - }; - return TraceAPI; -}()); + } +} exports.TraceAPI = TraceAPI; //# sourceMappingURL=trace.js.map @@ -47378,12 +47606,13 @@ exports.TraceAPI = TraceAPI; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0; -var context_1 = __nccwpck_require__(8242); +exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; +const context_1 = __nccwpck_require__(7171); +const context_2 = __nccwpck_require__(8242); /** * Baggage key */ -var BAGGAGE_KEY = context_1.createContextKey('OpenTelemetry Baggage Key'); +const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); /** * Retrieve the current baggage from the given context * @@ -47394,6 +47623,15 @@ function getBaggage(context) { return context.getValue(BAGGAGE_KEY) || undefined; } exports.getBaggage = getBaggage; +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +function getActiveBaggage() { + return getBaggage(context_1.ContextAPI.getInstance().active()); +} +exports.getActiveBaggage = getActiveBaggage; /** * Store a baggage in the given context * @@ -47439,50 +47677,41 @@ exports.deleteBaggage = deleteBaggage; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaggageImpl = void 0; -var BaggageImpl = /** @class */ (function () { - function BaggageImpl(entries) { +class BaggageImpl { + constructor(entries) { this._entries = entries ? new Map(entries) : new Map(); } - BaggageImpl.prototype.getEntry = function (key) { - var entry = this._entries.get(key); + getEntry(key) { + const entry = this._entries.get(key); if (!entry) { return undefined; } return Object.assign({}, entry); - }; - BaggageImpl.prototype.getAllEntries = function () { - return Array.from(this._entries.entries()).map(function (_a) { - var k = _a[0], v = _a[1]; - return [k, v]; - }); - }; - BaggageImpl.prototype.setEntry = function (key, entry) { - var newBaggage = new BaggageImpl(this._entries); + } + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); newBaggage._entries.set(key, entry); return newBaggage; - }; - BaggageImpl.prototype.removeEntry = function (key) { - var newBaggage = new BaggageImpl(this._entries); + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); newBaggage._entries.delete(key); return newBaggage; - }; - BaggageImpl.prototype.removeEntries = function () { - var keys = []; - for (var _i = 0; _i < arguments.length; _i++) { - keys[_i] = arguments[_i]; - } - var newBaggage = new BaggageImpl(this._entries); - for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { - var key = keys_1[_a]; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { newBaggage._entries.delete(key); } return newBaggage; - }; - BaggageImpl.prototype.clear = function () { + } + clear() { return new BaggageImpl(); - }; - return BaggageImpl; -}()); + } +} exports.BaggageImpl = BaggageImpl; //# sourceMappingURL=baggage-impl.js.map @@ -47518,31 +47747,6 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); /***/ }), -/***/ 1508: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=types.js.map - -/***/ }), - /***/ 8136: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -47565,17 +47769,16 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -var diag_1 = __nccwpck_require__(1877); -var baggage_impl_1 = __nccwpck_require__(4811); -var symbol_1 = __nccwpck_require__(3542); -var diag = diag_1.DiagAPI.instance(); +const diag_1 = __nccwpck_require__(1877); +const baggage_impl_1 = __nccwpck_require__(4811); +const symbol_1 = __nccwpck_require__(3542); +const diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries * * @param entries An array of baggage entries the new baggage should contain */ -function createBaggage(entries) { - if (entries === void 0) { entries = {}; } +function createBaggage(entries = {}) { return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); } exports.createBaggage = createBaggage; @@ -47587,12 +47790,12 @@ exports.createBaggage = createBaggage; */ function baggageEntryMetadataFromString(str) { if (typeof str !== 'string') { - diag.error("Cannot create baggage metadata from unknown type: " + typeof str); + diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); str = ''; } return { __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString: function () { + toString() { return str; }, }; @@ -47602,8 +47805,8 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; /***/ }), -/***/ 4447: -/***/ ((__unused_webpack_module, exports) => { +/***/ 7393: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -47623,22 +47826,18 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=Exception.js.map - -/***/ }), - -/***/ 656: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=Time.js.map +exports.context = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_1 = __nccwpck_require__(7171); +/** Entrypoint for context API */ +exports.context = context_1.ContextAPI.getInstance(); +//# sourceMappingURL=context-api.js.map /***/ }), /***/ 4118: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -47657,38 +47856,26 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * See the License for the specific language governing permissions and * limitations under the License. */ -var __spreadArray = (this && this.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; -var context_1 = __nccwpck_require__(8242); -var NoopContextManager = /** @class */ (function () { - function NoopContextManager() { - } - NoopContextManager.prototype.active = function () { +const context_1 = __nccwpck_require__(8242); +class NoopContextManager { + active() { return context_1.ROOT_CONTEXT; - }; - NoopContextManager.prototype.with = function (_context, fn, thisArg) { - var args = []; - for (var _i = 3; _i < arguments.length; _i++) { - args[_i - 3] = arguments[_i]; - } - return fn.call.apply(fn, __spreadArray([thisArg], args)); - }; - NoopContextManager.prototype.bind = function (_context, target) { + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { return target; - }; - NoopContextManager.prototype.enable = function () { + } + enable() { return this; - }; - NoopContextManager.prototype.disable = function () { + } + disable() { return this; - }; - return NoopContextManager; -}()); + } +} exports.NoopContextManager = NoopContextManager; //# sourceMappingURL=NoopContextManager.js.map @@ -47727,38 +47914,37 @@ function createContextKey(description) { return Symbol.for(description); } exports.createContextKey = createContextKey; -var BaseContext = /** @class */ (function () { +class BaseContext { /** * Construct a new context which inherits values from an optional parent context. * * @param parentContext a context from which to inherit values */ - function BaseContext(parentContext) { + constructor(parentContext) { // for minification - var self = this; + const self = this; self._currentContext = parentContext ? new Map(parentContext) : new Map(); - self.getValue = function (key) { return self._currentContext.get(key); }; - self.setValue = function (key, value) { - var context = new BaseContext(self._currentContext); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context = new BaseContext(self._currentContext); context._currentContext.set(key, value); return context; }; - self.deleteValue = function (key) { - var context = new BaseContext(self._currentContext); + self.deleteValue = (key) => { + const context = new BaseContext(self._currentContext); context._currentContext.delete(key); return context; }; } - return BaseContext; -}()); +} /** The root context is used as the default parent context when there is no active context */ exports.ROOT_CONTEXT = new BaseContext(); //# sourceMappingURL=context.js.map /***/ }), -/***/ 6504: -/***/ ((__unused_webpack_module, exports) => { +/***/ 9721: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -47778,7 +47964,18 @@ exports.ROOT_CONTEXT = new BaseContext(); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=types.js.map +exports.diag = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const diag_1 = __nccwpck_require__(1877); +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +exports.diag = diag_1.DiagAPI.instance(); +//# sourceMappingURL=diag-api.js.map /***/ }), @@ -47804,7 +48001,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; -var global_utils_1 = __nccwpck_require__(5135); +const global_utils_1 = __nccwpck_require__(5135); /** * Component Logger which is meant to be used as part of any component which * will add automatically additional namespace in front of the log message. @@ -47814,56 +48011,35 @@ var global_utils_1 = __nccwpck_require__(5135); * cLogger.debug('test'); * // @opentelemetry/instrumentation-http test */ -var DiagComponentLogger = /** @class */ (function () { - function DiagComponentLogger(props) { +class DiagComponentLogger { + constructor(props) { this._namespace = props.namespace || 'DiagComponentLogger'; } - DiagComponentLogger.prototype.debug = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + debug(...args) { return logProxy('debug', this._namespace, args); - }; - DiagComponentLogger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + } + error(...args) { return logProxy('error', this._namespace, args); - }; - DiagComponentLogger.prototype.info = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + } + info(...args) { return logProxy('info', this._namespace, args); - }; - DiagComponentLogger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + } + warn(...args) { return logProxy('warn', this._namespace, args); - }; - DiagComponentLogger.prototype.verbose = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + } + verbose(...args) { return logProxy('verbose', this._namespace, args); - }; - return DiagComponentLogger; -}()); + } +} exports.DiagComponentLogger = DiagComponentLogger; function logProxy(funcName, namespace, args) { - var logger = global_utils_1.getGlobal('diag'); + const logger = (0, global_utils_1.getGlobal)('diag'); // shortcut if logger not set if (!logger) { return; } args.unshift(namespace); - return logger[funcName].apply(logger, args); + return logger[funcName](...args); } //# sourceMappingURL=ComponentLogger.js.map @@ -47891,7 +48067,7 @@ function logProxy(funcName, namespace, args) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagConsoleLogger = void 0; -var consoleMap = [ +const consoleMap = [ { n: 'error', c: 'error' }, { n: 'warn', c: 'warn' }, { n: 'info', c: 'info' }, @@ -47903,18 +48079,14 @@ var consoleMap = [ * If you want to limit the amount of logging to a specific level or lower use the * {@link createLogLevelDiagLogger} */ -var DiagConsoleLogger = /** @class */ (function () { - function DiagConsoleLogger() { +class DiagConsoleLogger { + constructor() { function _consoleFunc(funcName) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + return function (...args) { if (console) { // Some environments only expose the console when the F12 developer console is open // eslint-disable-next-line no-console - var theFunc = console[funcName]; + let theFunc = console[funcName]; if (typeof theFunc !== 'function') { // Not all environments support all functions // eslint-disable-next-line no-console @@ -47927,54 +48099,16 @@ var DiagConsoleLogger = /** @class */ (function () { } }; } - for (var i = 0; i < consoleMap.length; i++) { + for (let i = 0; i < consoleMap.length; i++) { this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); } } - return DiagConsoleLogger; -}()); +} exports.DiagConsoleLogger = DiagConsoleLogger; //# sourceMappingURL=consoleLogger.js.map /***/ }), -/***/ 1634: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(3041), exports); -__exportStar(__nccwpck_require__(8077), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - /***/ 9639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -47997,7 +48131,7 @@ __exportStar(__nccwpck_require__(8077), exports); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; -var types_1 = __nccwpck_require__(8077); +const types_1 = __nccwpck_require__(8077); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; @@ -48008,7 +48142,7 @@ function createLogLevelDiagLogger(maxLevel, logger) { // In case the logger is null or undefined logger = logger || {}; function _filterFunc(funcName, theLevel) { - var theFunc = logger[funcName]; + const theFunc = logger[funcName]; if (typeof theFunc === 'function' && maxLevel >= theLevel) { return theFunc.bind(logger); } @@ -48079,7 +48213,7 @@ var DiagLogLevel; /***/ }), /***/ 5163: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -48098,40 +48232,42 @@ var DiagLogLevel; * See the License for the specific language governing permissions and * limitations under the License. */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.baggageEntryMetadataFromString = void 0; -__exportStar(__nccwpck_require__(1508), exports); +exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; var utils_1 = __nccwpck_require__(8136); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); -__exportStar(__nccwpck_require__(4447), exports); -__exportStar(__nccwpck_require__(656), exports); -__exportStar(__nccwpck_require__(1634), exports); -__exportStar(__nccwpck_require__(865), exports); -__exportStar(__nccwpck_require__(7492), exports); -__exportStar(__nccwpck_require__(4023), exports); -__exportStar(__nccwpck_require__(3503), exports); -__exportStar(__nccwpck_require__(2285), exports); -__exportStar(__nccwpck_require__(9671), exports); -__exportStar(__nccwpck_require__(3209), exports); -__exportStar(__nccwpck_require__(5769), exports); -__exportStar(__nccwpck_require__(1424), exports); -__exportStar(__nccwpck_require__(4416), exports); -__exportStar(__nccwpck_require__(955), exports); -__exportStar(__nccwpck_require__(8845), exports); -__exportStar(__nccwpck_require__(6905), exports); -__exportStar(__nccwpck_require__(8384), exports); -__exportStar(__nccwpck_require__(891), exports); -__exportStar(__nccwpck_require__(3168), exports); +// Context APIs +var context_1 = __nccwpck_require__(8242); +Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); +Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); +// Diag APIs +var consoleLogger_1 = __nccwpck_require__(3041); +Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); +var types_1 = __nccwpck_require__(8077); +Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); +// Metrics APIs +var NoopMeter_1 = __nccwpck_require__(4837); +Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); +var Metric_1 = __nccwpck_require__(9999); +Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); +// Propagation APIs +var TextMapPropagator_1 = __nccwpck_require__(865); +Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); +Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); +var ProxyTracer_1 = __nccwpck_require__(3503); +Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); +var ProxyTracerProvider_1 = __nccwpck_require__(2285); +Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); +var SamplingResult_1 = __nccwpck_require__(3209); +Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); +var span_kind_1 = __nccwpck_require__(1424); +Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); +var status_1 = __nccwpck_require__(8845); +Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); +var trace_flags_1 = __nccwpck_require__(6905); +Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); +var utils_2 = __nccwpck_require__(2615); +Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); var spancontext_utils_1 = __nccwpck_require__(9745); Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); @@ -48140,30 +48276,25 @@ var invalid_span_constants_1 = __nccwpck_require__(1760); Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); -__exportStar(__nccwpck_require__(8242), exports); -__exportStar(__nccwpck_require__(6504), exports); -var context_1 = __nccwpck_require__(7171); -/** Entrypoint for context API */ -exports.context = context_1.ContextAPI.getInstance(); -var trace_1 = __nccwpck_require__(1539); -/** Entrypoint for trace API */ -exports.trace = trace_1.TraceAPI.getInstance(); -var propagation_1 = __nccwpck_require__(9909); -/** Entrypoint for propagation API */ -exports.propagation = propagation_1.PropagationAPI.getInstance(); -var diag_1 = __nccwpck_require__(1877); -/** - * Entrypoint for Diag API. - * Defines Diagnostic handler used for internal diagnostic logging operations. - * The default provides a Noop DiagLogger implementation which may be changed via the - * diag.setLogger(logger: DiagLogger) function. - */ -exports.diag = diag_1.DiagAPI.instance(); +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_api_1 = __nccwpck_require__(7393); +Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); +const diag_api_1 = __nccwpck_require__(9721); +Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); +const metrics_api_1 = __nccwpck_require__(2601); +Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); +const propagation_api_1 = __nccwpck_require__(7591); +Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); +const trace_api_1 = __nccwpck_require__(8989); +Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); +// Default export. exports["default"] = { - trace: exports.trace, - context: exports.context, - propagation: exports.propagation, - diag: exports.diag, + context: context_api_1.context, + diag: diag_api_1.diag, + metrics: metrics_api_1.metrics, + propagation: propagation_api_1.propagation, + trace: trace_api_1.trace, }; //# sourceMappingURL=index.js.map @@ -48191,47 +48322,46 @@ exports["default"] = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -var platform_1 = __nccwpck_require__(9957); -var version_1 = __nccwpck_require__(8996); -var semver_1 = __nccwpck_require__(1522); -var major = version_1.VERSION.split('.')[0]; -var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); -var _global = platform_1._globalThis; -function registerGlobal(type, instance, diag, allowOverride) { +const platform_1 = __nccwpck_require__(9957); +const version_1 = __nccwpck_require__(8996); +const semver_1 = __nccwpck_require__(1522); +const major = version_1.VERSION.split('.')[0]; +const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); +const _global = platform_1._globalThis; +function registerGlobal(type, instance, diag, allowOverride = false) { var _a; - if (allowOverride === void 0) { allowOverride = false; } - var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: version_1.VERSION, }); if (!allowOverride && api[type]) { // already registered an API of this type - var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); diag.error(err.stack || err.message); return false; } if (api.version !== version_1.VERSION) { // All registered APIs must be of the same version exactly - var err = new Error('@opentelemetry/api: All API registration versions must match'); + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); diag.error(err.stack || err.message); return false; } api[type] = instance; - diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + version_1.VERSION + "."); + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); return true; } exports.registerGlobal = registerGlobal; function getGlobal(type) { var _a, _b; - var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; - if (!globalVersion || !semver_1.isCompatible(globalVersion)) { + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { return; } return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } exports.getGlobal = getGlobal; function unregisterGlobal(type, diag) { - diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + version_1.VERSION + "."); - var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; } @@ -48263,8 +48393,8 @@ exports.unregisterGlobal = unregisterGlobal; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; -var version_1 = __nccwpck_require__(8996); -var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +const version_1 = __nccwpck_require__(8996); +const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. * @@ -48282,14 +48412,14 @@ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; * @param ownVersion version which should be checked against */ function _makeCompatibilityCheck(ownVersion) { - var acceptedVersions = new Set([ownVersion]); - var rejectedVersions = new Set(); - var myVersionMatch = ownVersion.match(re); + const acceptedVersions = new Set([ownVersion]); + const rejectedVersions = new Set(); + const myVersionMatch = ownVersion.match(re); if (!myVersionMatch) { // we cannot guarantee compatibility so we always return noop - return function () { return false; }; + return () => false; } - var ownVersionParsed = { + const ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], @@ -48316,13 +48446,13 @@ function _makeCompatibilityCheck(ownVersion) { if (rejectedVersions.has(globalVersion)) { return false; } - var globalVersionMatch = globalVersion.match(re); + const globalVersionMatch = globalVersion.match(re); if (!globalVersionMatch) { // cannot parse other version // we cannot guarantee compatibility so we always noop return _reject(globalVersion); } - var globalVersionParsed = { + const globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], @@ -48370,6 +48500,230 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); /***/ }), +/***/ 2601: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.metrics = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const metrics_1 = __nccwpck_require__(7696); +/** Entrypoint for metrics API */ +exports.metrics = metrics_1.MetricsAPI.getInstance(); +//# sourceMappingURL=metrics-api.js.map + +/***/ }), + +/***/ 9999: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ValueType = void 0; +/** The Type of value. It describes how the data is reported. */ +var ValueType; +(function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; +})(ValueType = exports.ValueType || (exports.ValueType = {})); +//# sourceMappingURL=Metric.js.map + +/***/ }), + +/***/ 4837: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +class NoopMeter { + constructor() { } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return exports.NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return exports.NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return exports.NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return exports.NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { } +} +exports.NoopMeter = NoopMeter; +class NoopMetric { +} +exports.NoopMetric = NoopMetric; +class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopCounterMetric = NoopCounterMetric; +class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; +class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) { } +} +exports.NoopHistogramMetric = NoopHistogramMetric; +class NoopObservableMetric { + addCallback(_callback) { } + removeCallback(_callback) { } +} +exports.NoopObservableMetric = NoopObservableMetric; +class NoopObservableCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableCounterMetric = NoopObservableCounterMetric; +class NoopObservableGaugeMetric extends NoopObservableMetric { +} +exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; +class NoopObservableUpDownCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; +exports.NOOP_METER = new NoopMeter(); +// Synchronous instruments +exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); +exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); +exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); +// Asynchronous instruments +exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); +exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); +exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); +/** + * Create a no-op Meter + */ +function createNoopMeter() { + return exports.NOOP_METER; +} +exports.createNoopMeter = createNoopMeter; +//# sourceMappingURL=NoopMeter.js.map + +/***/ }), + +/***/ 2647: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; +const NoopMeter_1 = __nccwpck_require__(4837); +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NoopMeter_1.NOOP_METER; + } +} +exports.NoopMeterProvider = NoopMeterProvider; +exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); +//# sourceMappingURL=NoopMeterProvider.js.map + +/***/ }), + /***/ 9957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -48471,6 +48825,37 @@ __exportStar(__nccwpck_require__(9406), exports); /***/ }), +/***/ 7591: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.propagation = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const propagation_1 = __nccwpck_require__(9909); +/** Entrypoint for propagation API */ +exports.propagation = propagation_1.PropagationAPI.getInstance(); +//# sourceMappingURL=propagation-api.js.map + +/***/ }), + /***/ 2368: /***/ ((__unused_webpack_module, exports) => { @@ -48496,20 +48881,17 @@ exports.NoopTextMapPropagator = void 0; /** * No-op implementations of {@link TextMapPropagator}. */ -var NoopTextMapPropagator = /** @class */ (function () { - function NoopTextMapPropagator() { - } +class NoopTextMapPropagator { /** Noop inject function does nothing */ - NoopTextMapPropagator.prototype.inject = function (_context, _carrier) { }; + inject(_context, _carrier) { } /** Noop extract function does nothing and returns the input context */ - NoopTextMapPropagator.prototype.extract = function (context, _carrier) { + extract(context, _carrier) { return context; - }; - NoopTextMapPropagator.prototype.fields = function () { + } + fields() { return []; - }; - return NoopTextMapPropagator; -}()); + } +} exports.NoopTextMapPropagator = NoopTextMapPropagator; //# sourceMappingURL=NoopTextMapPropagator.js.map @@ -48538,13 +48920,13 @@ exports.NoopTextMapPropagator = NoopTextMapPropagator; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; exports.defaultTextMapGetter = { - get: function (carrier, key) { + get(carrier, key) { if (carrier == null) { return undefined; } return carrier[key]; }, - keys: function (carrier) { + keys(carrier) { if (carrier == null) { return []; } @@ -48552,7 +48934,7 @@ exports.defaultTextMapGetter = { }, }; exports.defaultTextMapSetter = { - set: function (carrier, key, value) { + set(carrier, key, value) { if (carrier == null) { return; } @@ -48563,6 +48945,37 @@ exports.defaultTextMapSetter = { /***/ }), +/***/ 8989: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.trace = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const trace_1 = __nccwpck_require__(1539); +/** Entrypoint for trace API */ +exports.trace = trace_1.TraceAPI.getInstance(); +//# sourceMappingURL=trace-api.js.map + +/***/ }), + /***/ 1462: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -48585,51 +48998,49 @@ exports.defaultTextMapSetter = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; -var invalid_span_constants_1 = __nccwpck_require__(1760); +const invalid_span_constants_1 = __nccwpck_require__(1760); /** * The NonRecordingSpan is the default {@link Span} that is used when no Span * implementation is available. All operations are no-op including context * propagation. */ -var NonRecordingSpan = /** @class */ (function () { - function NonRecordingSpan(_spanContext) { - if (_spanContext === void 0) { _spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT; } +class NonRecordingSpan { + constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { this._spanContext = _spanContext; } // Returns a SpanContext. - NonRecordingSpan.prototype.spanContext = function () { + spanContext() { return this._spanContext; - }; + } // By default does nothing - NonRecordingSpan.prototype.setAttribute = function (_key, _value) { + setAttribute(_key, _value) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.setAttributes = function (_attributes) { + setAttributes(_attributes) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.addEvent = function (_name, _attributes) { + addEvent(_name, _attributes) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.setStatus = function (_status) { + setStatus(_status) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.updateName = function (_name) { + updateName(_name) { return this; - }; + } // By default does nothing - NonRecordingSpan.prototype.end = function (_endTime) { }; + end(_endTime) { } // isRecording always returns false for NonRecordingSpan. - NonRecordingSpan.prototype.isRecording = function () { + isRecording() { return false; - }; + } // By default does nothing - NonRecordingSpan.prototype.recordException = function (_exception, _time) { }; - return NonRecordingSpan; -}()); + recordException(_exception, _time) { } +} exports.NonRecordingSpan = NonRecordingSpan; //# sourceMappingURL=NonRecordingSpan.js.map @@ -48657,36 +49068,34 @@ exports.NonRecordingSpan = NonRecordingSpan; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; -var context_1 = __nccwpck_require__(7171); -var context_utils_1 = __nccwpck_require__(3326); -var NonRecordingSpan_1 = __nccwpck_require__(1462); -var spancontext_utils_1 = __nccwpck_require__(9745); -var context = context_1.ContextAPI.getInstance(); +const context_1 = __nccwpck_require__(7171); +const context_utils_1 = __nccwpck_require__(3326); +const NonRecordingSpan_1 = __nccwpck_require__(1462); +const spancontext_utils_1 = __nccwpck_require__(9745); +const contextApi = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. */ -var NoopTracer = /** @class */ (function () { - function NoopTracer() { - } +class NoopTracer { // startSpan starts a noop span. - NoopTracer.prototype.startSpan = function (name, options, context) { - var root = Boolean(options === null || options === void 0 ? void 0 : options.root); + startSpan(name, options, context = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan_1.NonRecordingSpan(); } - var parentFromContext = context && context_utils_1.getSpanContext(context); + const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); if (isSpanContext(parentFromContext) && - spancontext_utils_1.isSpanContextValid(parentFromContext)) { + (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); } else { return new NonRecordingSpan_1.NonRecordingSpan(); } - }; - NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { - var opts; - var ctx; - var fn; + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; if (arguments.length < 2) { return; } @@ -48702,13 +49111,12 @@ var NoopTracer = /** @class */ (function () { ctx = arg3; fn = arg4; } - var parentContext = ctx !== null && ctx !== void 0 ? ctx : context.active(); - var span = this.startSpan(name, opts, parentContext); - var contextWithSpanSet = context_utils_1.setSpan(parentContext, span); - return context.with(contextWithSpanSet, fn, undefined, span); - }; - return NoopTracer; -}()); + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); + } +} exports.NoopTracer = NoopTracer; function isSpanContext(spanContext) { return (typeof spanContext === 'object' && @@ -48742,21 +49150,18 @@ function isSpanContext(spanContext) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; -var NoopTracer_1 = __nccwpck_require__(7606); +const NoopTracer_1 = __nccwpck_require__(7606); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. * * All operations are no-op. */ -var NoopTracerProvider = /** @class */ (function () { - function NoopTracerProvider() { - } - NoopTracerProvider.prototype.getTracer = function (_name, _version) { +class NoopTracerProvider { + getTracer(_name, _version, _options) { return new NoopTracer_1.NoopTracer(); - }; - return NoopTracerProvider; -}()); + } +} exports.NoopTracerProvider = NoopTracerProvider; //# sourceMappingURL=NoopTracerProvider.js.map @@ -48784,41 +49189,41 @@ exports.NoopTracerProvider = NoopTracerProvider; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; -var NoopTracer_1 = __nccwpck_require__(7606); -var NOOP_TRACER = new NoopTracer_1.NoopTracer(); +const NoopTracer_1 = __nccwpck_require__(7606); +const NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider */ -var ProxyTracer = /** @class */ (function () { - function ProxyTracer(_provider, name, version) { +class ProxyTracer { + constructor(_provider, name, version, options) { this._provider = _provider; this.name = name; this.version = version; + this.options = options; } - ProxyTracer.prototype.startSpan = function (name, options, context) { + startSpan(name, options, context) { return this._getTracer().startSpan(name, options, context); - }; - ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) { - var tracer = this._getTracer(); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); - }; + } /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. */ - ProxyTracer.prototype._getTracer = function () { + _getTracer() { if (this._delegate) { return this._delegate; } - var tracer = this._provider.getDelegateTracer(this.name, this.version); + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER; } this._delegate = tracer; return this._delegate; - }; - return ProxyTracer; -}()); + } +} exports.ProxyTracer = ProxyTracer; //# sourceMappingURL=ProxyTracer.js.map @@ -48846,9 +49251,9 @@ exports.ProxyTracer = ProxyTracer; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; -var ProxyTracer_1 = __nccwpck_require__(3503); -var NoopTracerProvider_1 = __nccwpck_require__(3259); -var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); +const ProxyTracer_1 = __nccwpck_require__(3503); +const NoopTracerProvider_1 = __nccwpck_require__(3259); +const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. * @@ -48857,62 +49262,34 @@ var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); * When a delegate is set after tracers have already been provided, * all tracers already provided will use the provided delegate implementation. */ -var ProxyTracerProvider = /** @class */ (function () { - function ProxyTracerProvider() { - } +class ProxyTracerProvider { /** * Get a {@link ProxyTracer} */ - ProxyTracerProvider.prototype.getTracer = function (name, version) { + getTracer(name, version, options) { var _a; - return ((_a = this.getDelegateTracer(name, version)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version)); - }; - ProxyTracerProvider.prototype.getDelegate = function () { + return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); + } + getDelegate() { var _a; return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; - }; + } /** * Set the delegate tracer provider */ - ProxyTracerProvider.prototype.setDelegate = function (delegate) { + setDelegate(delegate) { this._delegate = delegate; - }; - ProxyTracerProvider.prototype.getDelegateTracer = function (name, version) { + } + getDelegateTracer(name, version, options) { var _a; - return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version); - }; - return ProxyTracerProvider; -}()); + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); + } +} exports.ProxyTracerProvider = ProxyTracerProvider; //# sourceMappingURL=ProxyTracerProvider.js.map /***/ }), -/***/ 9671: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=Sampler.js.map - -/***/ }), - /***/ 3209: /***/ ((__unused_webpack_module, exports) => { @@ -48936,6 +49313,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SamplingDecision = void 0; /** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. * A sampling decision that determines how a {@link Span} will be recorded * and collected. */ @@ -48961,56 +49339,6 @@ var SamplingDecision; /***/ }), -/***/ 955: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=SpanOptions.js.map - -/***/ }), - -/***/ 7492: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=attributes.js.map - -/***/ }), - /***/ 3326: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -49032,13 +49360,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0; -var context_1 = __nccwpck_require__(8242); -var NonRecordingSpan_1 = __nccwpck_require__(1462); +exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; +const context_1 = __nccwpck_require__(8242); +const NonRecordingSpan_1 = __nccwpck_require__(1462); +const context_2 = __nccwpck_require__(7171); /** * span key */ -var SPAN_KEY = context_1.createContextKey('OpenTelemetry Context Key SPAN'); +const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); /** * Return the span if one exists * @@ -49048,6 +49377,13 @@ function getSpan(context) { return context.getValue(SPAN_KEY) || undefined; } exports.getSpan = getSpan; +/** + * Gets the span from the current context, if one exists. + */ +function getActiveSpan() { + return getSpan(context_2.ContextAPI.getInstance().active()); +} +exports.getActiveSpan = getActiveSpan; /** * Set the span on a context * @@ -49092,7 +49428,7 @@ exports.getSpanContext = getSpanContext; /***/ }), -/***/ 1760: +/***/ 2110: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49113,20 +49449,96 @@ exports.getSpanContext = getSpanContext; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -var trace_flags_1 = __nccwpck_require__(6905); -exports.INVALID_SPANID = '0000000000000000'; -exports.INVALID_TRACEID = '00000000000000000000000000000000'; -exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, -}; -//# sourceMappingURL=invalid-span-constants.js.map +exports.TraceStateImpl = void 0; +const tracestate_validators_1 = __nccwpck_require__(4864); +const MAX_TRACE_STATE_ITEMS = 32; +const MAX_TRACE_STATE_LEN = 512; +const LIST_MEMBERS_SEPARATOR = ','; +const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys() + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { + agg.set(key, value); + } + else { + // TODO: Consider to add warning log + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } +} +exports.TraceStateImpl = TraceStateImpl; +//# sourceMappingURL=tracestate-impl.js.map /***/ }), -/***/ 4023: +/***/ 4864: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49147,12 +49559,40 @@ exports.INVALID_SPAN_CONTEXT = { * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=link.js.map +exports.validateValue = exports.validateKey = void 0; +const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; +const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; +const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; +const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); +const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +exports.validateKey = validateKey; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); +} +exports.validateValue = validateValue; +//# sourceMappingURL=tracestate-validators.js.map /***/ }), -/***/ 4416: -/***/ ((__unused_webpack_module, exports) => { +/***/ 2615: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49172,12 +49612,18 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=span.js.map +exports.createTraceState = void 0; +const tracestate_impl_1 = __nccwpck_require__(2110); +function createTraceState(rawTraceState) { + return new tracestate_impl_1.TraceStateImpl(rawTraceState); +} +exports.createTraceState = createTraceState; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 5769: -/***/ ((__unused_webpack_module, exports) => { +/***/ 1760: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49197,7 +49643,16 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=span_context.js.map +exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +const trace_flags_1 = __nccwpck_require__(6905); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map /***/ }), @@ -49276,10 +49731,10 @@ exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = e * See the License for the specific language governing permissions and * limitations under the License. */ -var invalid_span_constants_1 = __nccwpck_require__(1760); -var NonRecordingSpan_1 = __nccwpck_require__(1462); -var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; -var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +const invalid_span_constants_1 = __nccwpck_require__(1760); +const NonRecordingSpan_1 = __nccwpck_require__(1462); +const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; } @@ -49373,81 +49828,6 @@ var TraceFlags; /***/ }), -/***/ 8384: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=trace_state.js.map - -/***/ }), - -/***/ 3168: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=tracer.js.map - -/***/ }), - -/***/ 891: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=tracer_provider.js.map - -/***/ }), - /***/ 8996: /***/ ((__unused_webpack_module, exports) => { @@ -49471,7 +49851,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.0.4'; +exports.VERSION = '1.4.1'; //# sourceMappingURL=version.js.map /***/ }), From 813556063c575b60f9440ce1c7db44c5c5e9810a Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Mon, 24 Apr 2023 11:19:22 +0200 Subject: [PATCH 07/21] Apply change request fixes --- dist/cache-save/index.js | 3406 +++++++++++++++++--------------------- dist/setup/index.js | 3406 +++++++++++++++++--------------------- src/cache-utils.ts | 13 +- 3 files changed, 3035 insertions(+), 3790 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index c974b0872..6a0ff626b 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -6980,18 +6980,19 @@ function copyFile(srcFile, destFile, force) { /***/ }), /***/ 2557: -/***/ ((__unused_webpack_module, exports) => { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib = __nccwpck_require__(9268); + // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/// -const listenersMap = new WeakMap(); -const abortedMap = new WeakMap(); +var listenersMap = new WeakMap(); +var abortedMap = new WeakMap(); /** * An aborter instance implements AbortSignal interface, can abort HTTP requests. * @@ -7005,8 +7006,8 @@ const abortedMap = new WeakMap(); * await doAsyncWork(AbortSignal.none); * ``` */ -class AbortSignal { - constructor() { +var AbortSignal = /** @class */ (function () { + function AbortSignal() { /** * onabort event listener. */ @@ -7014,65 +7015,74 @@ class AbortSignal { listenersMap.set(this, []); abortedMap.set(this, false); } - /** - * Status of whether aborted or not. - * - * @readonly - */ - get aborted() { - if (!abortedMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - return abortedMap.get(this); - } - /** - * Creates a new AbortSignal instance that will never be aborted. - * - * @readonly - */ - static get none() { - return new AbortSignal(); - } + Object.defineProperty(AbortSignal.prototype, "aborted", { + /** + * Status of whether aborted or not. + * + * @readonly + */ + get: function () { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + return abortedMap.get(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbortSignal, "none", { + /** + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + */ + get: function () { + return new AbortSignal(); + }, + enumerable: false, + configurable: true + }); /** * Added new "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be added */ - addEventListener( + AbortSignal.prototype.addEventListener = function ( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - const listeners = listenersMap.get(this); + var listeners = listenersMap.get(this); listeners.push(listener); - } + }; /** * Remove "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be removed */ - removeEventListener( + AbortSignal.prototype.removeEventListener = function ( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - const listeners = listenersMap.get(this); - const index = listeners.indexOf(listener); + var listeners = listenersMap.get(this); + var index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } - } + }; /** * Dispatches a synthetic event to the AbortSignal. */ - dispatchEvent(_event) { + AbortSignal.prototype.dispatchEvent = function (_event) { throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); - } -} + }; + return AbortSignal; +}()); /** * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. * Will try to trigger abort event for all linked AbortSignal nodes. @@ -7090,12 +7100,12 @@ function abortSignal(signal) { if (signal.onabort) { signal.onabort.call(signal); } - const listeners = listenersMap.get(signal); + var listeners = listenersMap.get(signal); if (listeners) { // Create a copy of listeners so mutations to the array // (e.g. via removeListener calls) don't affect the listeners // we invoke. - listeners.slice().forEach((listener) => { + listeners.slice().forEach(function (listener) { listener.call(signal, { type: "abort" }); }); } @@ -7121,12 +7131,15 @@ function abortSignal(signal) { * } * ``` */ -class AbortError extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; +var AbortError = /** @class */ (function (_super) { + tslib.__extends(AbortError, _super); + function AbortError(message) { + var _this = _super.call(this, message) || this; + _this.name = "AbortError"; + return _this; } -} + return AbortError; +}(Error)); /** * An AbortController provides an AbortSignal and the associated controls to signal * that an asynchronous operation should be aborted. @@ -7161,9 +7174,10 @@ class AbortError extends Error { * await doAsyncWork(aborter.withTimeout(25 * 1000)); * ``` */ -class AbortController { +var AbortController = /** @class */ (function () { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - constructor(parentSignals) { + function AbortController(parentSignals) { + var _this = this; this._signal = new AbortSignal(); if (!parentSignals) { return; @@ -7173,7 +7187,8 @@ class AbortController { // eslint-disable-next-line prefer-rest-params parentSignals = arguments; } - for (const parentSignal of parentSignals) { + for (var _i = 0, parentSignals_1 = parentSignals; _i < parentSignals_1.length; _i++) { + var parentSignal = parentSignals_1[_i]; // if the parent signal has already had abort() called, // then call abort on this signal as well. if (parentSignal.aborted) { @@ -7181,42 +7196,47 @@ class AbortController { } else { // when the parent signal aborts, this signal should as well. - parentSignal.addEventListener("abort", () => { - this.abort(); + parentSignal.addEventListener("abort", function () { + _this.abort(); }); } } } - /** - * The AbortSignal associated with this controller that will signal aborted - * when the abort method is called on this controller. - * - * @readonly - */ - get signal() { - return this._signal; - } + Object.defineProperty(AbortController.prototype, "signal", { + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + get: function () { + return this._signal; + }, + enumerable: false, + configurable: true + }); /** * Signal that any operations passed this controller's associated abort signal * to cancel any remaining work and throw an `AbortError`. */ - abort() { + AbortController.prototype.abort = function () { abortSignal(this._signal); - } + }; /** * Creates a new AbortSignal instance that will abort after the provided ms. * @param ms - Elapsed time in milliseconds to trigger an abort. */ - static timeout(ms) { - const signal = new AbortSignal(); - const timer = setTimeout(abortSignal, ms, signal); + AbortController.timeout = function (ms) { + var signal = new AbortSignal(); + var timer = setTimeout(abortSignal, ms, signal); // Prevent the active Timer from keeping the Node.js event loop active. if (typeof timer.unref === "function") { timer.unref(); } return signal; - } -} + }; + return AbortController; +}()); exports.AbortController = AbortController; exports.AbortError = AbortError; @@ -7224,6 +7244,333 @@ exports.AbortSignal = AbortSignal; //# sourceMappingURL=index.js.map +/***/ }), + +/***/ 9268: +/***/ ((module) => { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), + +/***/ 2356: +/***/ (() => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +if (typeof Symbol === undefined || !Symbol.asyncIterator) { + Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); +} +//# sourceMappingURL=index.js.map + /***/ }), /***/ 9645: @@ -14486,689 +14833,6 @@ exports["default"] = _default; Object.defineProperty(exports, "__esModule", ({ value: true })); var logger$1 = __nccwpck_require__(3233); -var abortController = __nccwpck_require__(2557); -var coreUtil = __nccwpck_require__(1333); - -// Copyright (c) Microsoft Corporation. -/** - * The `@azure/logger` configuration for this package. - * @internal - */ -const logger = logger$1.createClientLogger("core-lro"); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * The default time interval to wait before sending the next polling request. - */ -const POLL_INTERVAL_IN_MS = 2000; -/** - * The closed set of terminal states. - */ -const terminalStates = ["succeeded", "canceled", "failed"]; - -// Copyright (c) Microsoft Corporation. -/** - * Deserializes the state - */ -function deserializeState(serializedState) { - try { - return JSON.parse(serializedState).state; - } - catch (e) { - throw new Error(`Unable to deserialize input state: ${serializedState}`); - } -} -function setStateError(inputs) { - const { state, stateProxy, isOperationError } = inputs; - return (error) => { - if (isOperationError(error)) { - stateProxy.setError(state, error); - stateProxy.setFailed(state); - } - throw error; - }; -} -function processOperationStatus(result) { - const { state, stateProxy, status, isDone, processResult, response, setErrorAsResult } = result; - switch (status) { - case "succeeded": { - stateProxy.setSucceeded(state); - break; - } - case "failed": { - stateProxy.setError(state, new Error(`The long-running operation has failed`)); - stateProxy.setFailed(state); - break; - } - case "canceled": { - stateProxy.setCanceled(state); - break; - } - } - if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || - (isDone === undefined && - ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) { - stateProxy.setResult(state, buildResult({ - response, - state, - processResult, - })); - } -} -function buildResult(inputs) { - const { processResult, response, state } = inputs; - return processResult ? processResult(response, state) : response; -} -/** - * Initiates the long-running operation. - */ -async function initOperation(inputs) { - const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs; - const { operationLocation, resourceLocation, metadata, response } = await init(); - if (operationLocation) - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); - const config = { - metadata, - operationLocation, - resourceLocation, - }; - logger.verbose(`LRO: Operation description:`, config); - const state = stateProxy.initState(config); - const status = getOperationStatus({ response, state, operationLocation }); - processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult }); - return state; -} -async function pollOperationHelper(inputs) { - const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs; - const response = await poll(operationLocation, options).catch(setStateError({ - state, - stateProxy, - isOperationError, - })); - const status = getOperationStatus(response, state); - logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); - if (status === "succeeded") { - const resourceLocation = getResourceLocation(response, state); - if (resourceLocation !== undefined) { - return { - response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })), - status, - }; - } - } - return { response, status }; -} -/** Polls the long-running operation. */ -async function pollOperation(inputs) { - const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, updateState, setDelay, isDone, setErrorAsResult, } = inputs; - const { operationLocation } = state.config; - if (operationLocation !== undefined) { - const { response, status } = await pollOperationHelper({ - poll, - getOperationStatus, - state, - stateProxy, - operationLocation, - getResourceLocation, - isOperationError, - options, - }); - processOperationStatus({ - status, - response, - state, - stateProxy, - isDone, - processResult, - setErrorAsResult, - }); - if (!terminalStates.includes(status)) { - const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); - if (intervalInMs) - setDelay(intervalInMs); - const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state); - if (location !== undefined) { - const isUpdated = operationLocation !== location; - state.config.operationLocation = location; - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated); - } - else - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); - } - updateState === null || updateState === void 0 ? void 0 : updateState(state, response); - } -} - -// Copyright (c) Microsoft Corporation. -function getOperationLocationPollingUrl(inputs) { - const { azureAsyncOperation, operationLocation } = inputs; - return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; -} -function getLocationHeader(rawResponse) { - return rawResponse.headers["location"]; -} -function getOperationLocationHeader(rawResponse) { - return rawResponse.headers["operation-location"]; -} -function getAzureAsyncOperationHeader(rawResponse) { - return rawResponse.headers["azure-asyncoperation"]; -} -function findResourceLocation(inputs) { - const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; - switch (requestMethod) { - case "PUT": { - return requestPath; - } - case "DELETE": { - return undefined; - } - default: { - switch (resourceLocationConfig) { - case "azure-async-operation": { - return undefined; - } - case "original-uri": { - return requestPath; - } - case "location": - default: { - return location; - } - } - } - } -} -function inferLroMode(inputs) { - const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs; - const operationLocation = getOperationLocationHeader(rawResponse); - const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse); - const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation }); - const location = getLocationHeader(rawResponse); - const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase(); - if (pollingUrl !== undefined) { - return { - mode: "OperationLocation", - operationLocation: pollingUrl, - resourceLocation: findResourceLocation({ - requestMethod: normalizedRequestMethod, - location, - requestPath, - resourceLocationConfig, - }), - }; - } - else if (location !== undefined) { - return { - mode: "ResourceLocation", - operationLocation: location, - }; - } - else if (normalizedRequestMethod === "PUT" && requestPath) { - return { - mode: "Body", - operationLocation: requestPath, - }; - } - else { - return undefined; - } -} -function transformStatus(inputs) { - const { status, statusCode } = inputs; - if (typeof status !== "string" && status !== undefined) { - throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`); - } - switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) { - case undefined: - return toOperationStatus(statusCode); - case "succeeded": - return "succeeded"; - case "failed": - return "failed"; - case "running": - case "accepted": - case "started": - case "canceling": - case "cancelling": - return "running"; - case "canceled": - case "cancelled": - return "canceled"; - default: { - logger.verbose(`LRO: unrecognized operation status: ${status}`); - return status; - } - } -} -function getStatus(rawResponse) { - var _a; - const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - return transformStatus({ status, statusCode: rawResponse.statusCode }); -} -function getProvisioningState(rawResponse) { - var _a, _b; - const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; - return transformStatus({ status, statusCode: rawResponse.statusCode }); -} -function toOperationStatus(statusCode) { - if (statusCode === 202) { - return "running"; - } - else if (statusCode < 300) { - return "succeeded"; - } - else { - return "failed"; - } -} -function parseRetryAfter({ rawResponse }) { - const retryAfter = rawResponse.headers["retry-after"]; - if (retryAfter !== undefined) { - // Retry-After header value is either in HTTP date format, or in seconds - const retryAfterInSeconds = parseInt(retryAfter); - return isNaN(retryAfterInSeconds) - ? calculatePollingIntervalFromDate(new Date(retryAfter)) - : retryAfterInSeconds * 1000; - } - return undefined; -} -function calculatePollingIntervalFromDate(retryAfterDate) { - const timeNow = Math.floor(new Date().getTime()); - const retryAfterTime = retryAfterDate.getTime(); - if (timeNow < retryAfterTime) { - return retryAfterTime - timeNow; - } - return undefined; -} -function getStatusFromInitialResponse(inputs) { - const { response, state, operationLocation } = inputs; - function helper() { - var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case undefined: - return toOperationStatus(response.rawResponse.statusCode); - case "Body": - return getOperationStatus(response, state); - default: - return "running"; - } - } - const status = helper(); - return status === "running" && operationLocation === undefined ? "succeeded" : status; -} -/** - * Initiates the long-running operation. - */ -async function initHttpOperation(inputs) { - const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs; - return initOperation({ - init: async () => { - const response = await lro.sendInitialRequest(); - const config = inferLroMode({ - rawResponse: response.rawResponse, - requestPath: lro.requestPath, - requestMethod: lro.requestMethod, - resourceLocationConfig, - }); - return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); - }, - stateProxy, - processResult: processResult - ? ({ flatResponse }, state) => processResult(flatResponse, state) - : ({ flatResponse }) => flatResponse, - getOperationStatus: getStatusFromInitialResponse, - setErrorAsResult, - }); -} -function getOperationLocation({ rawResponse }, state) { - var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case "OperationLocation": { - return getOperationLocationPollingUrl({ - operationLocation: getOperationLocationHeader(rawResponse), - azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse), - }); - } - case "ResourceLocation": { - return getLocationHeader(rawResponse); - } - case "Body": - default: { - return undefined; - } - } -} -function getOperationStatus({ rawResponse }, state) { - var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case "OperationLocation": { - return getStatus(rawResponse); - } - case "ResourceLocation": { - return toOperationStatus(rawResponse.statusCode); - } - case "Body": { - return getProvisioningState(rawResponse); - } - default: - throw new Error(`Internal error: Unexpected operation mode: ${mode}`); - } -} -function getResourceLocation({ flatResponse }, state) { - if (typeof flatResponse === "object") { - const resourceLocation = flatResponse.resourceLocation; - if (resourceLocation !== undefined) { - state.config.resourceLocation = resourceLocation; - } - } - return state.config.resourceLocation; -} -function isOperationError(e) { - return e.name === "RestError"; -} -/** Polls the long-running operation. */ -async function pollHttpOperation(inputs) { - const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs; - return pollOperation({ - state, - stateProxy, - setDelay, - processResult: processResult - ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState) - : ({ flatResponse }) => flatResponse, - updateState, - getPollingInterval: parseRetryAfter, - getOperationLocation, - getOperationStatus, - isOperationError, - getResourceLocation, - options, - /** - * The expansion here is intentional because `lro` could be an object that - * references an inner this, so we need to preserve a reference to it. - */ - poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions), - setErrorAsResult, - }); -} - -// Copyright (c) Microsoft Corporation. -const createStateProxy$1 = () => ({ - /** - * The state at this point is created to be of type OperationState. - * It will be updated later to be of type TState when the - * customer-provided callback, `updateState`, is called during polling. - */ - initState: (config) => ({ status: "running", config }), - setCanceled: (state) => (state.status = "canceled"), - setError: (state, error) => (state.error = error), - setResult: (state, result) => (state.result = result), - setRunning: (state) => (state.status = "running"), - setSucceeded: (state) => (state.status = "succeeded"), - setFailed: (state) => (state.status = "failed"), - getError: (state) => state.error, - getResult: (state) => state.result, - isCanceled: (state) => state.status === "canceled", - isFailed: (state) => state.status === "failed", - isRunning: (state) => state.status === "running", - isSucceeded: (state) => state.status === "succeeded", -}); -/** - * Returns a poller factory. - */ -function buildCreatePoller(inputs) { - const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, resolveOnUnsuccessful, } = inputs; - return async ({ init, poll }, options) => { - const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {}; - const stateProxy = createStateProxy$1(); - const withOperationLocation = withOperationLocationCallback - ? (() => { - let called = false; - return (operationLocation, isUpdated) => { - if (isUpdated) - withOperationLocationCallback(operationLocation); - else if (!called) - withOperationLocationCallback(operationLocation); - called = true; - }; - })() - : undefined; - const state = restoreFrom - ? deserializeState(restoreFrom) - : await initOperation({ - init, - stateProxy, - processResult, - getOperationStatus: getStatusFromInitialResponse, - withOperationLocation, - setErrorAsResult: !resolveOnUnsuccessful, - }); - let resultPromise; - const abortController$1 = new abortController.AbortController(); - const handlers = new Map(); - const handleProgressEvents = async () => handlers.forEach((h) => h(state)); - const cancelErrMsg = "Operation was canceled"; - let currentPollIntervalInMs = intervalInMs; - const poller = { - getOperationState: () => state, - getResult: () => state.result, - isDone: () => ["succeeded", "failed", "canceled"].includes(state.status), - isStopped: () => resultPromise === undefined, - stopPolling: () => { - abortController$1.abort(); - }, - toString: () => JSON.stringify({ - state, - }), - onProgress: (callback) => { - const s = Symbol(); - handlers.set(s, callback); - return () => handlers.delete(s); - }, - pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => { - const { abortSignal: inputAbortSignal } = pollOptions || {}; - const { signal: abortSignal } = inputAbortSignal - ? new abortController.AbortController([inputAbortSignal, abortController$1.signal]) - : abortController$1; - if (!poller.isDone()) { - await poller.poll({ abortSignal }); - while (!poller.isDone()) { - await coreUtil.delay(currentPollIntervalInMs, { abortSignal }); - await poller.poll({ abortSignal }); - } - } - if (resolveOnUnsuccessful) { - return poller.getResult(); - } - else { - switch (state.status) { - case "succeeded": - return poller.getResult(); - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - case "notStarted": - case "running": - throw new Error(`Polling completed without succeeding or failing`); - } - } - })().finally(() => { - resultPromise = undefined; - }))), - async poll(pollOptions) { - if (resolveOnUnsuccessful) { - if (poller.isDone()) - return; - } - else { - switch (state.status) { - case "succeeded": - return; - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - } - } - await pollOperation({ - poll, - state, - stateProxy, - getOperationLocation, - isOperationError, - withOperationLocation, - getPollingInterval, - getOperationStatus: getStatusFromPollResponse, - getResourceLocation, - processResult, - updateState, - options: pollOptions, - setDelay: (pollIntervalInMs) => { - currentPollIntervalInMs = pollIntervalInMs; - }, - setErrorAsResult: !resolveOnUnsuccessful, - }); - await handleProgressEvents(); - if (!resolveOnUnsuccessful) { - switch (state.status) { - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - } - } - }, - }; - return poller; - }; -} - -// Copyright (c) Microsoft Corporation. -/** - * Creates a poller that can be used to poll a long-running operation. - * @param lro - Description of the long-running operation - * @param options - options to configure the poller - * @returns an initialized poller - */ -async function createHttpPoller(lro, options) { - const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {}; - return buildCreatePoller({ - getStatusFromInitialResponse, - getStatusFromPollResponse: getOperationStatus, - isOperationError, - getOperationLocation, - getResourceLocation, - getPollingInterval: parseRetryAfter, - resolveOnUnsuccessful, - })({ - init: async () => { - const response = await lro.sendInitialRequest(); - const config = inferLroMode({ - rawResponse: response.rawResponse, - requestPath: lro.requestPath, - requestMethod: lro.requestMethod, - resourceLocationConfig, - }); - return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); - }, - poll: lro.sendPollRequest, - }, { - intervalInMs, - withOperationLocation, - restoreFrom, - updateState, - processResult: processResult - ? ({ flatResponse }, state) => processResult(flatResponse, state) - : ({ flatResponse }) => flatResponse, - }); -} - -// Copyright (c) Microsoft Corporation. -const createStateProxy = () => ({ - initState: (config) => ({ config, isStarted: true }), - setCanceled: (state) => (state.isCancelled = true), - setError: (state, error) => (state.error = error), - setResult: (state, result) => (state.result = result), - setRunning: (state) => (state.isStarted = true), - setSucceeded: (state) => (state.isCompleted = true), - setFailed: () => { - /** empty body */ - }, - getError: (state) => state.error, - getResult: (state) => state.result, - isCanceled: (state) => !!state.isCancelled, - isFailed: (state) => !!state.error, - isRunning: (state) => !!state.isStarted, - isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error), -}); -class GenericPollOperation { - constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) { - this.state = state; - this.lro = lro; - this.setErrorAsResult = setErrorAsResult; - this.lroResourceLocationConfig = lroResourceLocationConfig; - this.processResult = processResult; - this.updateState = updateState; - this.isDone = isDone; - } - setPollerConfig(pollerConfig) { - this.pollerConfig = pollerConfig; - } - async update(options) { - var _a; - const stateProxy = createStateProxy(); - if (!this.state.isStarted) { - this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({ - lro: this.lro, - stateProxy, - resourceLocationConfig: this.lroResourceLocationConfig, - processResult: this.processResult, - setErrorAsResult: this.setErrorAsResult, - }))); - } - const updateState = this.updateState; - const isDone = this.isDone; - if (!this.state.isCompleted && this.state.error === undefined) { - await pollHttpOperation({ - lro: this.lro, - state: this.state, - stateProxy, - processResult: this.processResult, - updateState: updateState - ? (state, { rawResponse }) => updateState(state, rawResponse) - : undefined, - isDone: isDone - ? ({ flatResponse }, state) => isDone(flatResponse, state) - : undefined, - options, - setDelay: (intervalInMs) => { - this.pollerConfig.intervalInMs = intervalInMs; - }, - setErrorAsResult: this.setErrorAsResult, - }); - } - (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state); - return this; - } - async cancel() { - logger.error("`cancelOperation` is deprecated because it wasn't implemented"); - return this; - } - /** - * Serializes the Poller operation. - */ - toString() { - return JSON.stringify({ - state: this.state, - }); - } -} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -15184,8 +14848,8 @@ class PollerStoppedError extends Error { } } /** - * When the operation is cancelled, the poller will be rejected with an instance - * of the PollerCancelledError. + * When a poller is cancelled through the `cancelOperation` method, + * the poller will be rejected with an instance of the PollerCancelledError. */ class PollerCancelledError extends Error { constructor(message) { @@ -15323,8 +14987,6 @@ class Poller { * @param operation - Must contain the basic properties of `PollOperation`. */ constructor(operation) { - /** controls whether to throw an error if the operation failed or was canceled. */ - this.resolveOnUnsuccessful = false; this.stopped = true; this.pollProgressCallbacks = []; this.operation = operation; @@ -15343,12 +15005,12 @@ class Poller { * Starts a loop that will break only if the poller is done * or if the poller is stopped. */ - async startPolling(pollOptions = {}) { + async startPolling() { if (this.stopped) { this.stopped = false; } while (!this.isStopped() && !this.isDone()) { - await this.poll(pollOptions); + await this.poll(); await this.delay(); } } @@ -15361,13 +15023,29 @@ class Poller { * @param options - Optional properties passed to the operation's update method. */ async pollOnce(options = {}) { - if (!this.isDone()) { - this.operation = await this.operation.update({ - abortSignal: options.abortSignal, - fireProgress: this.fireProgress.bind(this), - }); + try { + if (!this.isDone()) { + this.operation = await this.operation.update({ + abortSignal: options.abortSignal, + fireProgress: this.fireProgress.bind(this), + }); + if (this.isDone() && this.resolve) { + // If the poller has finished polling, this means we now have a result. + // However, it can be the case that TResult is instantiated to void, so + // we are not expecting a result anyway. To assert that we might not + // have a result eventually after finishing polling, we cast the result + // to TResult. + this.resolve(this.operation.state.result); + } + } + } + catch (e) { + this.operation.state.error = e; + if (this.reject) { + this.reject(e); + } + throw e; } - this.processUpdatedState(); } /** * fireProgress calls the functions passed in via onProgress the method of the poller. @@ -15383,10 +15061,14 @@ class Poller { } } /** - * Invokes the underlying operation's cancel method. + * Invokes the underlying operation's cancel method, and rejects the + * pollUntilDone promise. */ async cancelOnce(options = {}) { this.operation = await this.operation.cancel(options); + if (this.reject) { + this.reject(new PollerCancelledError("Poller cancelled")); + } } /** * Returns a promise that will resolve once a single polling request finishes. @@ -15406,41 +15088,13 @@ class Poller { } return this.pollOncePromise; } - processUpdatedState() { - if (this.operation.state.error) { - this.stopped = true; - if (!this.resolveOnUnsuccessful) { - this.reject(this.operation.state.error); - throw this.operation.state.error; - } - } - if (this.operation.state.isCancelled) { - this.stopped = true; - if (!this.resolveOnUnsuccessful) { - const error = new PollerCancelledError("Operation was canceled"); - this.reject(error); - throw error; - } - } - if (this.isDone() && this.resolve) { - // If the poller has finished polling, this means we now have a result. - // However, it can be the case that TResult is instantiated to void, so - // we are not expecting a result anyway. To assert that we might not - // have a result eventually after finishing polling, we cast the result - // to TResult. - this.resolve(this.getResult()); - } - } /** * Returns a promise that will resolve once the underlying operation is completed. */ - async pollUntilDone(pollOptions = {}) { + async pollUntilDone() { if (this.stopped) { - this.startPolling(pollOptions).catch(this.reject); + this.startPolling().catch(this.reject); } - // This is needed because the state could have been updated by - // `cancelOperation`, e.g. the operation is canceled or an error occurred. - this.processUpdatedState(); return this.promise; } /** @@ -15489,6 +15143,9 @@ class Poller { * @param options - Optional properties passed to the operation's update method. */ cancelOperation(options = {}) { + if (!this.stopped) { + this.stopped = true; + } if (!this.cancelPromise) { this.cancelPromise = this.cancelOnce(options); } @@ -15568,18 +15225,344 @@ class Poller { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Detects where the continuation token is and returns it. Notice that azure-asyncoperation + * must be checked first before the other location headers because there are scenarios + * where both azure-asyncoperation and location could be present in the same response but + * azure-asyncoperation should be the one to use for polling. + */ +function getPollingUrl(rawResponse, defaultPath) { + var _a, _b, _c; + return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getOperationLocation(rawResponse)) !== null && _b !== void 0 ? _b : getLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath); +} +function getLocation(rawResponse) { + return rawResponse.headers["location"]; +} +function getOperationLocation(rawResponse) { + return rawResponse.headers["operation-location"]; +} +function getAzureAsyncOperation(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; +} +function findResourceLocation(requestMethod, rawResponse, requestPath) { + switch (requestMethod) { + case "PUT": { + return requestPath; + } + case "POST": + case "PATCH": { + return getLocation(rawResponse); + } + default: { + return undefined; + } + } +} +function inferLroMode(requestPath, requestMethod, rawResponse) { + if (getAzureAsyncOperation(rawResponse) !== undefined || + getOperationLocation(rawResponse) !== undefined) { + return { + mode: "Location", + resourceLocation: findResourceLocation(requestMethod, rawResponse, requestPath), + }; + } + else if (getLocation(rawResponse) !== undefined) { + return { + mode: "Location", + }; + } + else if (["PUT", "PATCH"].includes(requestMethod)) { + return { + mode: "Body", + }; + } + return {}; +} +class SimpleRestError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "RestError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, SimpleRestError.prototype); + } +} +function isUnexpectedInitialResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![203, 204, 202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code); + } + return false; +} +function isUnexpectedPollingResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); + } + return false; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const successStates = ["succeeded"]; +const failureStates = ["failed", "canceled", "cancelled"]; + +// Copyright (c) Microsoft Corporation. +function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return typeof state === "string" ? state.toLowerCase() : "succeeded"; +} +function isBodyPollingDone(rawResponse) { + const state = getProvisioningState(rawResponse); + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Creates a polling strategy based on BodyPolling which uses the provisioning state + * from the result to determine the current operation state + */ +function processBodyPollingOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) }); +} + +// Copyright (c) Microsoft Corporation. +/** + * The `@azure/logger` configuration for this package. + * @internal + */ +const logger = logger$1.createClientLogger("core-lro"); + +// Copyright (c) Microsoft Corporation. +function isPollingDone(rawResponse) { + var _a; + if (isUnexpectedPollingResponse(rawResponse) || rawResponse.statusCode === 202) { + return false; + } + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = typeof status === "string" ? status.toLowerCase() : "succeeded"; + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Sends a request to the URI of the provisioned resource if needed. + */ +async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) { + switch (lroResourceLocationConfig) { + case "original-uri": + return lro.sendPollRequest(lro.requestPath); + case "azure-async-operation": + return undefined; + case "location": + default: + return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath); + } +} +function processLocationPollingOperationResult(lro, resourceLocation, lroResourceLocationConfig) { + return (response) => { + if (isPollingDone(response.rawResponse)) { + if (resourceLocation === undefined) { + return Object.assign(Object.assign({}, response), { done: true }); + } + else { + return Object.assign(Object.assign({}, response), { done: false, next: async () => { + const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig); + return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true }); + } }); + } + } + return Object.assign(Object.assign({}, response), { done: false }); + }; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +function processPassthroughOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: true }); +} + +// Copyright (c) Microsoft Corporation. +/** + * creates a stepping function that maps an LRO state to another. + */ +function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) { + switch (config.mode) { + case "Location": { + return processLocationPollingOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig); + } + case "Body": { + return processBodyPollingOperationResult; + } + default: { + return processPassthroughOperationResult; + } + } +} +/** + * Creates a polling operation. + */ +function createPoll(lroPrimitives) { + return async (path, pollerConfig, getLroStatusFromResponse) => { + const response = await lroPrimitives.sendPollRequest(path); + const retryAfter = response.rawResponse.headers["retry-after"]; + if (retryAfter !== undefined) { + // Retry-After header value is either in HTTP date format, or in seconds + const retryAfterInSeconds = parseInt(retryAfter); + pollerConfig.intervalInMs = isNaN(retryAfterInSeconds) + ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) + : retryAfterInSeconds * 1000; + } + return getLroStatusFromResponse(response); + }; +} +function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { + const timeNow = Math.floor(new Date().getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return defaultIntervalInMs; +} +/** + * Creates a callback to be used to initialize the polling operation state. + * @param state - of the polling operation + * @param operationSpec - of the LRO + * @param callback - callback to be called when the operation is done + * @returns callback that initializes the state of the polling operation + */ +function createInitializeState(state, requestPath, requestMethod) { + return (response) => { + if (isUnexpectedInitialResponse(response.rawResponse)) + ; + state.initialRawResponse = response.rawResponse; + state.isStarted = true; + state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath); + state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse); + /** short circuit polling if body polling is done in the initial request */ + if (state.config.mode === undefined || + (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) { + state.result = response.flatResponse; + state.isCompleted = true; + } + logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`); + return Boolean(state.isCompleted); + }; +} + +// Copyright (c) Microsoft Corporation. +class GenericPollOperation { + constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + /** + * General update function for LROPoller, the general process is as follows + * 1. Check initial operation result to determine the strategy to use + * - Strategies: Location, Azure-AsyncOperation, Original Uri + * 2. Check if the operation result has a terminal state + * - Terminal state will be determined by each strategy + * 2.1 If it is terminal state Check if a final GET request is required, if so + * send final GET request and return result from operation. If no final GET + * is required, just return the result from operation. + * - Determining what to call for final request is responsibility of each strategy + * 2.2 If it is not terminal state, call the polling operation and go to step 1 + * - Determining what to call for polling is responsibility of each strategy + * - Strategies will always use the latest URI for polling if provided otherwise + * the last known one + */ + async update(options) { + var _a, _b, _c; + const state = this.state; + let lastResponse = undefined; + if (!state.isStarted) { + const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod); + lastResponse = await this.lro.sendInitialRequest(); + initializeState(lastResponse); + } + if (!state.isCompleted) { + if (!this.poll || !this.getLroStatusFromResponse) { + if (!state.config) { + throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed."); + } + const isDone = this.isDone; + this.getLroStatusFromResponse = isDone + ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) + : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig); + this.poll = createPoll(this.lro); + } + if (!state.pollingURL) { + throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed."); + } + const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse); + logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`); + if (currentState.done) { + state.result = this.processResult + ? this.processResult(currentState.flatResponse, state) + : currentState.flatResponse; + state.isCompleted = true; + } + else { + this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; + state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL); + } + lastResponse = currentState; + } + logger.verbose(`LRO: current state: ${JSON.stringify(state)}`); + if (lastResponse) { + (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); + } + else { + logger.error(`LRO: no response was received`); + } + (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); + return this; + } + async cancel() { + this.state.isCancelled = true; + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state, + }); + } +} + +// Copyright (c) Microsoft Corporation. +function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; + } + catch (e) { + throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); + } +} /** * The LRO Engine, a class that performs polling. */ class LroEngine extends Poller { constructor(lro, options) { - const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {}; + const { intervalInMs = 2000, resumeFrom } = options || {}; const state = resumeFrom ? deserializeState(resumeFrom) : {}; - const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone); + const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone); super(operation); - this.resolveOnUnsuccessful = resolveOnUnsuccessful; this.config = { intervalInMs: intervalInMs }; operation.setPollerConfig(this.config); } @@ -15595,7 +15578,6 @@ exports.LroEngine = LroEngine; exports.Poller = Poller; exports.PollerCancelledError = PollerCancelledError; exports.PollerStoppedError = PollerStoppedError; -exports.createHttpPoller = createHttpPoller; //# sourceMappingURL=index.js.map @@ -15609,6 +15591,7 @@ exports.createHttpPoller = createHttpPoller; Object.defineProperty(exports, "__esModule", ({ value: true })); +__nccwpck_require__(2356); var tslib = __nccwpck_require__(6429); // Copyright (c) Microsoft Corporation. @@ -15630,78 +15613,47 @@ function getPagedAsyncIterator(pagedResult) { return this; }, byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => { - const { continuationToken, maxPageSize } = settings !== null && settings !== void 0 ? settings : {}; - return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, - maxPageSize, - }); + return getPageAsyncIterator(pagedResult, settings === null || settings === void 0 ? void 0 : settings.maxPageSize); }), }; } -function getItemAsyncIterator(pagedResult) { +function getItemAsyncIterator(pagedResult, maxPageSize) { return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() { - var e_1, _a, e_2, _b; - const pages = getPageAsyncIterator(pagedResult); + var e_1, _a; + const pages = getPageAsyncIterator(pagedResult, maxPageSize); const firstVal = yield tslib.__await(pages.next()); // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(firstVal.value)))); - try { - for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { - const page = pages_1_1.value; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(page)))); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); - } - finally { if (e_1) throw e_1.error; } - } - } - else { - yield yield tslib.__await(firstVal.value); - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); - } + yield yield tslib.__await(firstVal.value); + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); } else { yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value))); try { - for (var pages_2 = tslib.__asyncValues(pages), pages_2_1; pages_2_1 = yield tslib.__await(pages_2.next()), !pages_2_1.done;) { - const page = pages_2_1.value; + for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { + const page = pages_1_1.value; // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, // it must be the case that `TPage = TElement[]` yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page))); } } - catch (e_2_1) { e_2 = { error: e_2_1 }; } + catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (pages_2_1 && !pages_2_1.done && (_b = pages_2.return)) yield tslib.__await(_b.call(pages_2)); + if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); } - finally { if (e_2) throw e_2.error; } + finally { if (e_1) throw e_1.error; } } } }); } -function getPageAsyncIterator(pagedResult, options = {}) { +function getPageAsyncIterator(pagedResult, maxPageSize) { return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() { - const { pageLink, maxPageSize } = options; - let response = yield tslib.__await(pagedResult.getPage(pageLink !== null && pageLink !== void 0 ? pageLink : pagedResult.firstPageLink, maxPageSize)); - if (!response) { - return yield tslib.__await(void 0); - } + let response = yield tslib.__await(pagedResult.getPage(pagedResult.firstPageLink, maxPageSize)); yield yield tslib.__await(response.page); while (response.nextPageLink) { response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); - if (!response) { - return yield tslib.__await(void 0); - } yield yield tslib.__await(response.page); } }); @@ -15716,7 +15668,7 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator; /***/ 6429: /***/ ((module) => { -/****************************************************************************** +/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -15736,10 +15688,6 @@ var __assign; var __rest; var __decorate; var __param; -var __esDecorate; -var __runInitializers; -var __propKey; -var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -15758,7 +15706,6 @@ var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; -var __classPrivateFieldIn; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; @@ -15827,51 +15774,6 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; - __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.push(_); - } - else if (_ = accept(result)) { - if (kind === "field") initializers.push(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - - __runInitializers = function (thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; - }; - - __propKey = function (x) { - return typeof x === "symbol" ? x : "".concat(x); - }; - - __setFunctionName = function (f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); - }; - __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; @@ -15892,7 +15794,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { + while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -15920,11 +15822,7 @@ var __createBinding; __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -16004,7 +15902,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -16051,20 +15949,11 @@ var __createBinding; return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; - __classPrivateFieldIn = function (state, receiver) { - if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); - exporter("__esDecorate", __esDecorate); - exporter("__runInitializers", __runInitializers); - exporter("__propKey", __propKey); - exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -16084,7 +15973,6 @@ var __createBinding; exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); - exporter("__classPrivateFieldIn", __classPrivateFieldIn); }); @@ -16567,16 +16455,14 @@ exports.randomUUID = randomUUID; Object.defineProperty(exports, "__esModule", ({ value: true })); -var os = __nccwpck_require__(2037); -var util = __nccwpck_require__(3837); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var util__default = /*#__PURE__*/_interopDefaultLegacy(util); +var util = _interopDefault(__nccwpck_require__(3837)); +var os = __nccwpck_require__(2037); // Copyright (c) Microsoft Corporation. function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); + process.stderr.write(`${util.format(message, ...args)}${os.EOL}`); } // Copyright (c) Microsoft Corporation. @@ -16594,7 +16480,7 @@ const debugObj = Object.assign((namespace) => { enable, enabled, disable, - log, + log }); function enable(namespaces) { enabledString = namespaces; @@ -16641,7 +16527,7 @@ function createDebugger(namespace) { destroy, log: debugObj.log, namespace, - extend, + extend }); function debug(...args) { if (!newDebugger.enabled) { @@ -16668,7 +16554,6 @@ function extend(namespace) { newDebugger.log = this.log; return newDebugger; } -var debug = debugObj; // Copyright (c) Microsoft Corporation. const registeredLoggers = new Set(); @@ -16679,9 +16564,9 @@ let azureLogLevel; * By default, logs are sent to stderr. * Override the `log` method to redirect logs to another location. */ -const AzureLogger = debug("azure"); +const AzureLogger = debugObj("azure"); AzureLogger.log = (...args) => { - debug.log(...args); + debugObj.log(...args); }; const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; if (logLevelFromEnv) { @@ -16694,7 +16579,7 @@ if (logLevelFromEnv) { } } /** - * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. + * Immediately enables logging at the specified log level. * @param level - The log level to enable for logging. * Options from most verbose to least verbose are: * - verbose @@ -16713,7 +16598,7 @@ function setLogLevel(level) { enabledNamespaces.push(logger.namespace); } } - debug.enable(enabledNamespaces.join(",")); + debugObj.enable(enabledNamespaces.join(",")); } /** * Retrieves the currently specified log level. @@ -16725,7 +16610,7 @@ const levelMap = { verbose: 400, info: 300, warning: 200, - error: 100, + error: 100 }; /** * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. @@ -16739,7 +16624,7 @@ function createClientLogger(namespace) { error: createLogger(clientRootLogger, "error"), warning: createLogger(clientRootLogger, "warning"), info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose"), + verbose: createLogger(clientRootLogger, "verbose") }; } function patchLogMethod(parent, child) { @@ -16749,18 +16634,23 @@ function patchLogMethod(parent, child) { } function createLogger(parent, level) { const logger = Object.assign(parent.extend(level), { - level, + level }); patchLogMethod(parent, logger); if (shouldEnable(logger)) { - const enabledNamespaces = debug.disable(); - debug.enable(enabledNamespaces + "," + logger.namespace); + const enabledNamespaces = debugObj.disable(); + debugObj.enable(enabledNamespaces + "," + logger.namespace); } registeredLoggers.add(logger); return logger; } function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + if (azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]) { + return true; + } + else { + return false; + } } function isAzureLogLevel(logLevel) { return AZURE_LOG_LEVELS.includes(logLevel); @@ -41901,7 +41791,7 @@ exports.newPipeline = newPipeline; /***/ 679: /***/ ((module) => { -/****************************************************************************** +/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -41921,10 +41811,6 @@ var __assign; var __rest; var __decorate; var __param; -var __esDecorate; -var __runInitializers; -var __propKey; -var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -41943,7 +41829,6 @@ var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; -var __classPrivateFieldIn; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; @@ -42012,51 +41897,6 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; - __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.push(_); - } - else if (_ = accept(result)) { - if (kind === "field") initializers.push(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - - __runInitializers = function (thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; - }; - - __propKey = function (x) { - return typeof x === "symbol" ? x : "".concat(x); - }; - - __setFunctionName = function (f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); - }; - __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; @@ -42077,7 +41917,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { + while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -42105,11 +41945,7 @@ var __createBinding; __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -42189,7 +42025,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -42236,20 +42072,11 @@ var __createBinding; return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; - __classPrivateFieldIn = function (state, receiver) { - if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); - exporter("__esDecorate", __esDecorate); - exporter("__runInitializers", __runInitializers); - exporter("__propKey", __propKey); - exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -42269,14 +42096,13 @@ var __createBinding; exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); - exporter("__classPrivateFieldIn", __classPrivateFieldIn); }); /***/ }), /***/ 7171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -42295,40 +42121,46 @@ var __createBinding; * See the License for the specific language governing permissions and * limitations under the License. */ +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; -const NoopContextManager_1 = __nccwpck_require__(4118); -const global_utils_1 = __nccwpck_require__(5135); -const diag_1 = __nccwpck_require__(1877); -const API_NAME = 'context'; -const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); +var NoopContextManager_1 = __nccwpck_require__(4118); +var global_utils_1 = __nccwpck_require__(5135); +var diag_1 = __nccwpck_require__(1877); +var API_NAME = 'context'; +var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** * Singleton object which represents the entry point to the OpenTelemetry Context API */ -class ContextAPI { +var ContextAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } + function ContextAPI() { + } /** Get the singleton instance of the Context API */ - static getInstance() { + ContextAPI.getInstance = function () { if (!this._instance) { this._instance = new ContextAPI(); } return this._instance; - } + }; /** * Set the current context manager. * * @returns true if the context manager was successfully registered, else false */ - setGlobalContextManager(contextManager) { - return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); - } + ContextAPI.prototype.setGlobalContextManager = function (contextManager) { + return global_utils_1.registerGlobal(API_NAME, contextManager, diag_1.DiagAPI.instance()); + }; /** * Get the currently active context */ - active() { + ContextAPI.prototype.active = function () { return this._getContextManager().active(); - } + }; /** * Execute a function with an active context * @@ -42337,27 +42169,33 @@ class ContextAPI { * @param thisArg optional receiver to be used for calling fn * @param args optional arguments forwarded to fn */ - with(context, fn, thisArg, ...args) { - return this._getContextManager().with(context, fn, thisArg, ...args); - } + ContextAPI.prototype.with = function (context, fn, thisArg) { + var _a; + var args = []; + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], args)); + }; /** * Bind a context to a target function or event emitter * * @param context context to bind to the event emitter or function. Defaults to the currently active context * @param target function or event emitter to bind */ - bind(context, target) { + ContextAPI.prototype.bind = function (context, target) { return this._getContextManager().bind(context, target); - } - _getContextManager() { - return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; - } + }; + ContextAPI.prototype._getContextManager = function () { + return global_utils_1.getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER; + }; /** Disable and remove the global context manager */ - disable() { + ContextAPI.prototype.disable = function () { this._getContextManager().disable(); - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } -} + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); + }; + return ContextAPI; +}()); exports.ContextAPI = ContextAPI; //# sourceMappingURL=context.js.map @@ -42385,63 +42223,62 @@ exports.ContextAPI = ContextAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; -const ComponentLogger_1 = __nccwpck_require__(7978); -const logLevelLogger_1 = __nccwpck_require__(9639); -const types_1 = __nccwpck_require__(8077); -const global_utils_1 = __nccwpck_require__(5135); -const API_NAME = 'diag'; +var ComponentLogger_1 = __nccwpck_require__(7978); +var logLevelLogger_1 = __nccwpck_require__(9639); +var types_1 = __nccwpck_require__(8077); +var global_utils_1 = __nccwpck_require__(5135); +var API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal * diagnostic API */ -class DiagAPI { +var DiagAPI = /** @class */ (function () { /** * Private internal constructor * @private */ - constructor() { + function DiagAPI() { function _logProxy(funcName) { - return function (...args) { - const logger = (0, global_utils_1.getGlobal)('diag'); + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var logger = global_utils_1.getGlobal('diag'); // shortcut if logger not set if (!logger) return; - return logger[funcName](...args); + return logger[funcName].apply(logger, args); }; } // Using self local variable for minification purposes as 'this' cannot be minified - const self = this; + var self = this; // DiagAPI specific functions - const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { - var _a, _b, _c; + self.setLogger = function (logger, logLevel) { + var _a, _b; + if (logLevel === void 0) { logLevel = types_1.DiagLogLevel.INFO; } if (logger === self) { // There isn't much we can do here. // Logging to the console might break the user application. // Try to log to self. If a logger was previously registered it will receive the log. - const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); return false; } - if (typeof optionsOrLogLevel === 'number') { - optionsOrLogLevel = { - logLevel: optionsOrLogLevel, - }; - } - const oldLogger = (0, global_utils_1.getGlobal)('diag'); - const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); + var oldLogger = global_utils_1.getGlobal('diag'); + var newLogger = logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger); // There already is an logger registered. We'll let it know before overwriting it. - if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { - const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; - oldLogger.warn(`Current logger will be overwritten from ${stack}`); - newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + if (oldLogger) { + var stack = (_b = new Error().stack) !== null && _b !== void 0 ? _b : ''; + oldLogger.warn("Current logger will be overwritten from " + stack); + newLogger.warn("Current logger will overwrite one already registered from " + stack); } - return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); + return global_utils_1.registerGlobal('diag', newLogger, self, true); }; - self.setLogger = setLogger; - self.disable = () => { - (0, global_utils_1.unregisterGlobal)(API_NAME, self); + self.disable = function () { + global_utils_1.unregisterGlobal(API_NAME, self); }; - self.createComponentLogger = (options) => { + self.createComponentLogger = function (options) { return new ComponentLogger_1.DiagComponentLogger(options); }; self.verbose = _logProxy('verbose'); @@ -42451,86 +42288,19 @@ class DiagAPI { self.error = _logProxy('error'); } /** Get the singleton instance of the DiagAPI API */ - static instance() { + DiagAPI.instance = function () { if (!this._instance) { this._instance = new DiagAPI(); } return this._instance; - } -} + }; + return DiagAPI; +}()); exports.DiagAPI = DiagAPI; //# sourceMappingURL=diag.js.map /***/ }), -/***/ 7696: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MetricsAPI = void 0; -const NoopMeterProvider_1 = __nccwpck_require__(2647); -const global_utils_1 = __nccwpck_require__(5135); -const diag_1 = __nccwpck_require__(1877); -const API_NAME = 'metrics'; -/** - * Singleton object which represents the entry point to the OpenTelemetry Metrics API - */ -class MetricsAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } - /** Get the singleton instance of the Metrics API */ - static getInstance() { - if (!this._instance) { - this._instance = new MetricsAPI(); - } - return this._instance; - } - /** - * Set the current global meter provider. - * Returns true if the meter provider was successfully registered, else false. - */ - setGlobalMeterProvider(provider) { - return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); - } - /** - * Returns the global meter provider. - */ - getMeterProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; - } - /** - * Returns a meter from the global meter provider. - */ - getMeter(name, version, options) { - return this.getMeterProvider().getMeter(name, version, options); - } - /** Remove the global meter provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } -} -exports.MetricsAPI = MetricsAPI; -//# sourceMappingURL=metrics.js.map - -/***/ }), - /***/ 9909: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -42553,41 +42323,40 @@ exports.MetricsAPI = MetricsAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; -const global_utils_1 = __nccwpck_require__(5135); -const NoopTextMapPropagator_1 = __nccwpck_require__(2368); -const TextMapPropagator_1 = __nccwpck_require__(865); -const context_helpers_1 = __nccwpck_require__(7682); -const utils_1 = __nccwpck_require__(8136); -const diag_1 = __nccwpck_require__(1877); -const API_NAME = 'propagation'; -const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); +var global_utils_1 = __nccwpck_require__(5135); +var NoopTextMapPropagator_1 = __nccwpck_require__(2368); +var TextMapPropagator_1 = __nccwpck_require__(865); +var context_helpers_1 = __nccwpck_require__(7682); +var utils_1 = __nccwpck_require__(8136); +var diag_1 = __nccwpck_require__(1877); +var API_NAME = 'propagation'; +var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** * Singleton object which represents the entry point to the OpenTelemetry Propagation API */ -class PropagationAPI { +var PropagationAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { + function PropagationAPI() { this.createBaggage = utils_1.createBaggage; this.getBaggage = context_helpers_1.getBaggage; - this.getActiveBaggage = context_helpers_1.getActiveBaggage; this.setBaggage = context_helpers_1.setBaggage; this.deleteBaggage = context_helpers_1.deleteBaggage; } /** Get the singleton instance of the Propagator API */ - static getInstance() { + PropagationAPI.getInstance = function () { if (!this._instance) { this._instance = new PropagationAPI(); } return this._instance; - } + }; /** * Set the current propagator. * * @returns true if the propagator was successfully registered, else false */ - setGlobalPropagator(propagator) { - return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); - } + PropagationAPI.prototype.setGlobalPropagator = function (propagator) { + return global_utils_1.registerGlobal(API_NAME, propagator, diag_1.DiagAPI.instance()); + }; /** * Inject context into a carrier to be propagated inter-process * @@ -42595,9 +42364,10 @@ class PropagationAPI { * @param carrier carrier to inject context into * @param setter Function used to set values on the carrier */ - inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { + PropagationAPI.prototype.inject = function (context, carrier, setter) { + if (setter === void 0) { setter = TextMapPropagator_1.defaultTextMapSetter; } return this._getGlobalPropagator().inject(context, carrier, setter); - } + }; /** * Extract context from a carrier * @@ -42605,23 +42375,25 @@ class PropagationAPI { * @param carrier Carrier to extract context from * @param getter Function used to extract keys from a carrier */ - extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { + PropagationAPI.prototype.extract = function (context, carrier, getter) { + if (getter === void 0) { getter = TextMapPropagator_1.defaultTextMapGetter; } return this._getGlobalPropagator().extract(context, carrier, getter); - } + }; /** * Return a list of all fields which may be used by the propagator. */ - fields() { + PropagationAPI.prototype.fields = function () { return this._getGlobalPropagator().fields(); - } + }; /** Remove the global propagator */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } - _getGlobalPropagator() { - return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; - } -} + PropagationAPI.prototype.disable = function () { + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); + }; + PropagationAPI.prototype._getGlobalPropagator = function () { + return global_utils_1.getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + }; + return PropagationAPI; +}()); exports.PropagationAPI = PropagationAPI; //# sourceMappingURL=propagation.js.map @@ -42649,65 +42421,65 @@ exports.PropagationAPI = PropagationAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; -const global_utils_1 = __nccwpck_require__(5135); -const ProxyTracerProvider_1 = __nccwpck_require__(2285); -const spancontext_utils_1 = __nccwpck_require__(9745); -const context_utils_1 = __nccwpck_require__(3326); -const diag_1 = __nccwpck_require__(1877); -const API_NAME = 'trace'; +var global_utils_1 = __nccwpck_require__(5135); +var ProxyTracerProvider_1 = __nccwpck_require__(2285); +var spancontext_utils_1 = __nccwpck_require__(9745); +var context_utils_1 = __nccwpck_require__(3326); +var diag_1 = __nccwpck_require__(1877); +var API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API */ -class TraceAPI { +var TraceAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { + function TraceAPI() { this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; this.deleteSpan = context_utils_1.deleteSpan; this.getSpan = context_utils_1.getSpan; - this.getActiveSpan = context_utils_1.getActiveSpan; this.getSpanContext = context_utils_1.getSpanContext; this.setSpan = context_utils_1.setSpan; this.setSpanContext = context_utils_1.setSpanContext; } /** Get the singleton instance of the Trace API */ - static getInstance() { + TraceAPI.getInstance = function () { if (!this._instance) { this._instance = new TraceAPI(); } return this._instance; - } + }; /** * Set the current global tracer. * * @returns true if the tracer provider was successfully registered, else false */ - setGlobalTracerProvider(provider) { - const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + TraceAPI.prototype.setGlobalTracerProvider = function (provider) { + var success = global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); if (success) { this._proxyTracerProvider.setDelegate(provider); } return success; - } + }; /** * Returns the global tracer provider. */ - getTracerProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; - } + TraceAPI.prototype.getTracerProvider = function () { + return global_utils_1.getGlobal(API_NAME) || this._proxyTracerProvider; + }; /** * Returns a tracer from the global tracer provider. */ - getTracer(name, version) { + TraceAPI.prototype.getTracer = function (name, version) { return this.getTracerProvider().getTracer(name, version); - } + }; /** Remove the global tracer provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + TraceAPI.prototype.disable = function () { + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - } -} + }; + return TraceAPI; +}()); exports.TraceAPI = TraceAPI; //# sourceMappingURL=trace.js.map @@ -42734,13 +42506,12 @@ exports.TraceAPI = TraceAPI; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; -const context_1 = __nccwpck_require__(7171); -const context_2 = __nccwpck_require__(8242); +exports.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0; +var context_1 = __nccwpck_require__(8242); /** * Baggage key */ -const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); +var BAGGAGE_KEY = context_1.createContextKey('OpenTelemetry Baggage Key'); /** * Retrieve the current baggage from the given context * @@ -42751,15 +42522,6 @@ function getBaggage(context) { return context.getValue(BAGGAGE_KEY) || undefined; } exports.getBaggage = getBaggage; -/** - * Retrieve the current baggage from the active/current context - * - * @returns {Baggage} Extracted baggage from the context - */ -function getActiveBaggage() { - return getBaggage(context_1.ContextAPI.getInstance().active()); -} -exports.getActiveBaggage = getActiveBaggage; /** * Store a baggage in the given context * @@ -42805,41 +42567,50 @@ exports.deleteBaggage = deleteBaggage; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaggageImpl = void 0; -class BaggageImpl { - constructor(entries) { +var BaggageImpl = /** @class */ (function () { + function BaggageImpl(entries) { this._entries = entries ? new Map(entries) : new Map(); } - getEntry(key) { - const entry = this._entries.get(key); + BaggageImpl.prototype.getEntry = function (key) { + var entry = this._entries.get(key); if (!entry) { return undefined; } return Object.assign({}, entry); - } - getAllEntries() { - return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); - } - setEntry(key, entry) { - const newBaggage = new BaggageImpl(this._entries); + }; + BaggageImpl.prototype.getAllEntries = function () { + return Array.from(this._entries.entries()).map(function (_a) { + var k = _a[0], v = _a[1]; + return [k, v]; + }); + }; + BaggageImpl.prototype.setEntry = function (key, entry) { + var newBaggage = new BaggageImpl(this._entries); newBaggage._entries.set(key, entry); return newBaggage; - } - removeEntry(key) { - const newBaggage = new BaggageImpl(this._entries); + }; + BaggageImpl.prototype.removeEntry = function (key) { + var newBaggage = new BaggageImpl(this._entries); newBaggage._entries.delete(key); return newBaggage; - } - removeEntries(...keys) { - const newBaggage = new BaggageImpl(this._entries); - for (const key of keys) { + }; + BaggageImpl.prototype.removeEntries = function () { + var keys = []; + for (var _i = 0; _i < arguments.length; _i++) { + keys[_i] = arguments[_i]; + } + var newBaggage = new BaggageImpl(this._entries); + for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { + var key = keys_1[_a]; newBaggage._entries.delete(key); } return newBaggage; - } - clear() { + }; + BaggageImpl.prototype.clear = function () { return new BaggageImpl(); - } -} + }; + return BaggageImpl; +}()); exports.BaggageImpl = BaggageImpl; //# sourceMappingURL=baggage-impl.js.map @@ -42875,6 +42646,31 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); /***/ }), +/***/ 1508: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=types.js.map + +/***/ }), + /***/ 8136: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -42897,16 +42693,17 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -const diag_1 = __nccwpck_require__(1877); -const baggage_impl_1 = __nccwpck_require__(4811); -const symbol_1 = __nccwpck_require__(3542); -const diag = diag_1.DiagAPI.instance(); +var diag_1 = __nccwpck_require__(1877); +var baggage_impl_1 = __nccwpck_require__(4811); +var symbol_1 = __nccwpck_require__(3542); +var diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries * * @param entries An array of baggage entries the new baggage should contain */ -function createBaggage(entries = {}) { +function createBaggage(entries) { + if (entries === void 0) { entries = {}; } return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); } exports.createBaggage = createBaggage; @@ -42918,12 +42715,12 @@ exports.createBaggage = createBaggage; */ function baggageEntryMetadataFromString(str) { if (typeof str !== 'string') { - diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + diag.error("Cannot create baggage metadata from unknown type: " + typeof str); str = ''; } return { __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString() { + toString: function () { return str; }, }; @@ -42933,8 +42730,8 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; /***/ }), -/***/ 7393: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4447: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -42954,18 +42751,22 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.context = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const context_1 = __nccwpck_require__(7171); -/** Entrypoint for context API */ -exports.context = context_1.ContextAPI.getInstance(); -//# sourceMappingURL=context-api.js.map +//# sourceMappingURL=Exception.js.map + +/***/ }), + +/***/ 2358: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=Time.js.map /***/ }), /***/ 4118: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -42984,26 +42785,38 @@ exports.context = context_1.ContextAPI.getInstance(); * See the License for the specific language governing permissions and * limitations under the License. */ +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; -const context_1 = __nccwpck_require__(8242); -class NoopContextManager { - active() { - return context_1.ROOT_CONTEXT; - } - with(_context, fn, thisArg, ...args) { - return fn.call(thisArg, ...args); +var context_1 = __nccwpck_require__(8242); +var NoopContextManager = /** @class */ (function () { + function NoopContextManager() { } - bind(_context, target) { + NoopContextManager.prototype.active = function () { + return context_1.ROOT_CONTEXT; + }; + NoopContextManager.prototype.with = function (_context, fn, thisArg) { + var args = []; + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + return fn.call.apply(fn, __spreadArray([thisArg], args)); + }; + NoopContextManager.prototype.bind = function (_context, target) { return target; - } - enable() { + }; + NoopContextManager.prototype.enable = function () { return this; - } - disable() { + }; + NoopContextManager.prototype.disable = function () { return this; - } -} + }; + return NoopContextManager; +}()); exports.NoopContextManager = NoopContextManager; //# sourceMappingURL=NoopContextManager.js.map @@ -43042,37 +42855,38 @@ function createContextKey(description) { return Symbol.for(description); } exports.createContextKey = createContextKey; -class BaseContext { +var BaseContext = /** @class */ (function () { /** * Construct a new context which inherits values from an optional parent context. * * @param parentContext a context from which to inherit values */ - constructor(parentContext) { + function BaseContext(parentContext) { // for minification - const self = this; + var self = this; self._currentContext = parentContext ? new Map(parentContext) : new Map(); - self.getValue = (key) => self._currentContext.get(key); - self.setValue = (key, value) => { - const context = new BaseContext(self._currentContext); + self.getValue = function (key) { return self._currentContext.get(key); }; + self.setValue = function (key, value) { + var context = new BaseContext(self._currentContext); context._currentContext.set(key, value); return context; }; - self.deleteValue = (key) => { - const context = new BaseContext(self._currentContext); + self.deleteValue = function (key) { + var context = new BaseContext(self._currentContext); context._currentContext.delete(key); return context; }; } -} + return BaseContext; +}()); /** The root context is used as the default parent context when there is no active context */ exports.ROOT_CONTEXT = new BaseContext(); //# sourceMappingURL=context.js.map /***/ }), -/***/ 9721: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 6504: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -43092,18 +42906,7 @@ exports.ROOT_CONTEXT = new BaseContext(); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.diag = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const diag_1 = __nccwpck_require__(1877); -/** - * Entrypoint for Diag API. - * Defines Diagnostic handler used for internal diagnostic logging operations. - * The default provides a Noop DiagLogger implementation which may be changed via the - * diag.setLogger(logger: DiagLogger) function. - */ -exports.diag = diag_1.DiagAPI.instance(); -//# sourceMappingURL=diag-api.js.map +//# sourceMappingURL=types.js.map /***/ }), @@ -43129,7 +42932,7 @@ exports.diag = diag_1.DiagAPI.instance(); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; -const global_utils_1 = __nccwpck_require__(5135); +var global_utils_1 = __nccwpck_require__(5135); /** * Component Logger which is meant to be used as part of any component which * will add automatically additional namespace in front of the log message. @@ -43139,35 +42942,56 @@ const global_utils_1 = __nccwpck_require__(5135); * cLogger.debug('test'); * // @opentelemetry/instrumentation-http test */ -class DiagComponentLogger { - constructor(props) { +var DiagComponentLogger = /** @class */ (function () { + function DiagComponentLogger(props) { this._namespace = props.namespace || 'DiagComponentLogger'; } - debug(...args) { + DiagComponentLogger.prototype.debug = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('debug', this._namespace, args); - } - error(...args) { + }; + DiagComponentLogger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('error', this._namespace, args); - } - info(...args) { + }; + DiagComponentLogger.prototype.info = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('info', this._namespace, args); - } - warn(...args) { + }; + DiagComponentLogger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('warn', this._namespace, args); - } - verbose(...args) { + }; + DiagComponentLogger.prototype.verbose = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('verbose', this._namespace, args); - } -} + }; + return DiagComponentLogger; +}()); exports.DiagComponentLogger = DiagComponentLogger; function logProxy(funcName, namespace, args) { - const logger = (0, global_utils_1.getGlobal)('diag'); + var logger = global_utils_1.getGlobal('diag'); // shortcut if logger not set if (!logger) { return; } args.unshift(namespace); - return logger[funcName](...args); + return logger[funcName].apply(logger, args); } //# sourceMappingURL=ComponentLogger.js.map @@ -43195,7 +43019,7 @@ function logProxy(funcName, namespace, args) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagConsoleLogger = void 0; -const consoleMap = [ +var consoleMap = [ { n: 'error', c: 'error' }, { n: 'warn', c: 'warn' }, { n: 'info', c: 'info' }, @@ -43207,14 +43031,18 @@ const consoleMap = [ * If you want to limit the amount of logging to a specific level or lower use the * {@link createLogLevelDiagLogger} */ -class DiagConsoleLogger { - constructor() { +var DiagConsoleLogger = /** @class */ (function () { + function DiagConsoleLogger() { function _consoleFunc(funcName) { - return function (...args) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } if (console) { // Some environments only expose the console when the F12 developer console is open // eslint-disable-next-line no-console - let theFunc = console[funcName]; + var theFunc = console[funcName]; if (typeof theFunc !== 'function') { // Not all environments support all functions // eslint-disable-next-line no-console @@ -43227,16 +43055,54 @@ class DiagConsoleLogger { } }; } - for (let i = 0; i < consoleMap.length; i++) { + for (var i = 0; i < consoleMap.length; i++) { this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); } } -} + return DiagConsoleLogger; +}()); exports.DiagConsoleLogger = DiagConsoleLogger; //# sourceMappingURL=consoleLogger.js.map /***/ }), +/***/ 1634: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(3041), exports); +__exportStar(__nccwpck_require__(8077), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + /***/ 9639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -43259,7 +43125,7 @@ exports.DiagConsoleLogger = DiagConsoleLogger; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; -const types_1 = __nccwpck_require__(8077); +var types_1 = __nccwpck_require__(8077); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; @@ -43270,7 +43136,7 @@ function createLogLevelDiagLogger(maxLevel, logger) { // In case the logger is null or undefined logger = logger || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + var theFunc = logger[funcName]; if (typeof theFunc === 'function' && maxLevel >= theLevel) { return theFunc.bind(logger); } @@ -43341,7 +43207,7 @@ var DiagLogLevel; /***/ }), /***/ 5163: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -43360,42 +43226,40 @@ var DiagLogLevel; * See the License for the specific language governing permissions and * limitations under the License. */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; +exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.baggageEntryMetadataFromString = void 0; +__exportStar(__nccwpck_require__(1508), exports); var utils_1 = __nccwpck_require__(8136); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); -// Context APIs -var context_1 = __nccwpck_require__(8242); -Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); -Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); -// Diag APIs -var consoleLogger_1 = __nccwpck_require__(3041); -Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); -var types_1 = __nccwpck_require__(8077); -Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); -// Metrics APIs -var NoopMeter_1 = __nccwpck_require__(4837); -Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); -var Metric_1 = __nccwpck_require__(9999); -Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); -// Propagation APIs -var TextMapPropagator_1 = __nccwpck_require__(865); -Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); -Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); -var ProxyTracer_1 = __nccwpck_require__(3503); -Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); -var ProxyTracerProvider_1 = __nccwpck_require__(2285); -Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); -var SamplingResult_1 = __nccwpck_require__(3209); -Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); -var span_kind_1 = __nccwpck_require__(1424); -Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); -var status_1 = __nccwpck_require__(8845); -Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); -var trace_flags_1 = __nccwpck_require__(6905); -Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); -var utils_2 = __nccwpck_require__(2615); -Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); +__exportStar(__nccwpck_require__(4447), exports); +__exportStar(__nccwpck_require__(2358), exports); +__exportStar(__nccwpck_require__(1634), exports); +__exportStar(__nccwpck_require__(865), exports); +__exportStar(__nccwpck_require__(7492), exports); +__exportStar(__nccwpck_require__(4023), exports); +__exportStar(__nccwpck_require__(3503), exports); +__exportStar(__nccwpck_require__(2285), exports); +__exportStar(__nccwpck_require__(9671), exports); +__exportStar(__nccwpck_require__(3209), exports); +__exportStar(__nccwpck_require__(5769), exports); +__exportStar(__nccwpck_require__(1424), exports); +__exportStar(__nccwpck_require__(4416), exports); +__exportStar(__nccwpck_require__(955), exports); +__exportStar(__nccwpck_require__(8845), exports); +__exportStar(__nccwpck_require__(6905), exports); +__exportStar(__nccwpck_require__(8384), exports); +__exportStar(__nccwpck_require__(891), exports); +__exportStar(__nccwpck_require__(3168), exports); var spancontext_utils_1 = __nccwpck_require__(9745); Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); @@ -43404,25 +43268,30 @@ var invalid_span_constants_1 = __nccwpck_require__(1760); Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const context_api_1 = __nccwpck_require__(7393); -Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); -const diag_api_1 = __nccwpck_require__(9721); -Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); -const metrics_api_1 = __nccwpck_require__(2601); -Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); -const propagation_api_1 = __nccwpck_require__(7591); -Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); -const trace_api_1 = __nccwpck_require__(8989); -Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); -// Default export. +__exportStar(__nccwpck_require__(8242), exports); +__exportStar(__nccwpck_require__(6504), exports); +var context_1 = __nccwpck_require__(7171); +/** Entrypoint for context API */ +exports.context = context_1.ContextAPI.getInstance(); +var trace_1 = __nccwpck_require__(1539); +/** Entrypoint for trace API */ +exports.trace = trace_1.TraceAPI.getInstance(); +var propagation_1 = __nccwpck_require__(9909); +/** Entrypoint for propagation API */ +exports.propagation = propagation_1.PropagationAPI.getInstance(); +var diag_1 = __nccwpck_require__(1877); +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +exports.diag = diag_1.DiagAPI.instance(); exports["default"] = { - context: context_api_1.context, - diag: diag_api_1.diag, - metrics: metrics_api_1.metrics, - propagation: propagation_api_1.propagation, - trace: trace_api_1.trace, + trace: exports.trace, + context: exports.context, + propagation: exports.propagation, + diag: exports.diag, }; //# sourceMappingURL=index.js.map @@ -43450,46 +43319,47 @@ exports["default"] = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -const platform_1 = __nccwpck_require__(9957); -const version_1 = __nccwpck_require__(8996); -const semver_1 = __nccwpck_require__(1522); -const major = version_1.VERSION.split('.')[0]; -const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); -const _global = platform_1._globalThis; -function registerGlobal(type, instance, diag, allowOverride = false) { +var platform_1 = __nccwpck_require__(9957); +var version_1 = __nccwpck_require__(8996); +var semver_1 = __nccwpck_require__(1522); +var major = version_1.VERSION.split('.')[0]; +var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); +var _global = platform_1._globalThis; +function registerGlobal(type, instance, diag, allowOverride) { var _a; - const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + if (allowOverride === void 0) { allowOverride = false; } + var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: version_1.VERSION, }); if (!allowOverride && api[type]) { // already registered an API of this type - const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); diag.error(err.stack || err.message); return false; } if (api.version !== version_1.VERSION) { // All registered APIs must be of the same version exactly - const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); + var err = new Error('@opentelemetry/api: All API registration versions must match'); diag.error(err.stack || err.message); return false; } api[type] = instance; - diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); + diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + version_1.VERSION + "."); return true; } exports.registerGlobal = registerGlobal; function getGlobal(type) { var _a, _b; - const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; - if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { + var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !semver_1.isCompatible(globalVersion)) { return; } return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } exports.getGlobal = getGlobal; function unregisterGlobal(type, diag) { - diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); - const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + version_1.VERSION + "."); + var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; } @@ -43521,8 +43391,8 @@ exports.unregisterGlobal = unregisterGlobal; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; -const version_1 = __nccwpck_require__(8996); -const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +var version_1 = __nccwpck_require__(8996); +var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. * @@ -43540,14 +43410,14 @@ const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; * @param ownVersion version which should be checked against */ function _makeCompatibilityCheck(ownVersion) { - const acceptedVersions = new Set([ownVersion]); - const rejectedVersions = new Set(); - const myVersionMatch = ownVersion.match(re); + var acceptedVersions = new Set([ownVersion]); + var rejectedVersions = new Set(); + var myVersionMatch = ownVersion.match(re); if (!myVersionMatch) { // we cannot guarantee compatibility so we always return noop - return () => false; + return function () { return false; }; } - const ownVersionParsed = { + var ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], @@ -43574,13 +43444,13 @@ function _makeCompatibilityCheck(ownVersion) { if (rejectedVersions.has(globalVersion)) { return false; } - const globalVersionMatch = globalVersion.match(re); + var globalVersionMatch = globalVersion.match(re); if (!globalVersionMatch) { // cannot parse other version // we cannot guarantee compatibility so we always noop return _reject(globalVersion); } - const globalVersionParsed = { + var globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], @@ -43628,230 +43498,6 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); /***/ }), -/***/ 2601: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.metrics = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const metrics_1 = __nccwpck_require__(7696); -/** Entrypoint for metrics API */ -exports.metrics = metrics_1.MetricsAPI.getInstance(); -//# sourceMappingURL=metrics-api.js.map - -/***/ }), - -/***/ 9999: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ValueType = void 0; -/** The Type of value. It describes how the data is reported. */ -var ValueType; -(function (ValueType) { - ValueType[ValueType["INT"] = 0] = "INT"; - ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; -})(ValueType = exports.ValueType || (exports.ValueType = {})); -//# sourceMappingURL=Metric.js.map - -/***/ }), - -/***/ 4837: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; -/** - * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses - * constant NoopMetrics for all of its methods. - */ -class NoopMeter { - constructor() { } - /** - * @see {@link Meter.createHistogram} - */ - createHistogram(_name, _options) { - return exports.NOOP_HISTOGRAM_METRIC; - } - /** - * @see {@link Meter.createCounter} - */ - createCounter(_name, _options) { - return exports.NOOP_COUNTER_METRIC; - } - /** - * @see {@link Meter.createUpDownCounter} - */ - createUpDownCounter(_name, _options) { - return exports.NOOP_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableGauge} - */ - createObservableGauge(_name, _options) { - return exports.NOOP_OBSERVABLE_GAUGE_METRIC; - } - /** - * @see {@link Meter.createObservableCounter} - */ - createObservableCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableUpDownCounter} - */ - createObservableUpDownCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.addBatchObservableCallback} - */ - addBatchObservableCallback(_callback, _observables) { } - /** - * @see {@link Meter.removeBatchObservableCallback} - */ - removeBatchObservableCallback(_callback) { } -} -exports.NoopMeter = NoopMeter; -class NoopMetric { -} -exports.NoopMetric = NoopMetric; -class NoopCounterMetric extends NoopMetric { - add(_value, _attributes) { } -} -exports.NoopCounterMetric = NoopCounterMetric; -class NoopUpDownCounterMetric extends NoopMetric { - add(_value, _attributes) { } -} -exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; -class NoopHistogramMetric extends NoopMetric { - record(_value, _attributes) { } -} -exports.NoopHistogramMetric = NoopHistogramMetric; -class NoopObservableMetric { - addCallback(_callback) { } - removeCallback(_callback) { } -} -exports.NoopObservableMetric = NoopObservableMetric; -class NoopObservableCounterMetric extends NoopObservableMetric { -} -exports.NoopObservableCounterMetric = NoopObservableCounterMetric; -class NoopObservableGaugeMetric extends NoopObservableMetric { -} -exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; -class NoopObservableUpDownCounterMetric extends NoopObservableMetric { -} -exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; -exports.NOOP_METER = new NoopMeter(); -// Synchronous instruments -exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); -exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); -exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); -// Asynchronous instruments -exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); -exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); -exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); -/** - * Create a no-op Meter - */ -function createNoopMeter() { - return exports.NOOP_METER; -} -exports.createNoopMeter = createNoopMeter; -//# sourceMappingURL=NoopMeter.js.map - -/***/ }), - -/***/ 2647: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; -const NoopMeter_1 = __nccwpck_require__(4837); -/** - * An implementation of the {@link MeterProvider} which returns an impotent Meter - * for all calls to `getMeter` - */ -class NoopMeterProvider { - getMeter(_name, _version, _options) { - return NoopMeter_1.NOOP_METER; - } -} -exports.NoopMeterProvider = NoopMeterProvider; -exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); -//# sourceMappingURL=NoopMeterProvider.js.map - -/***/ }), - /***/ 9957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -43953,37 +43599,6 @@ __exportStar(__nccwpck_require__(9406), exports); /***/ }), -/***/ 7591: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.propagation = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const propagation_1 = __nccwpck_require__(9909); -/** Entrypoint for propagation API */ -exports.propagation = propagation_1.PropagationAPI.getInstance(); -//# sourceMappingURL=propagation-api.js.map - -/***/ }), - /***/ 2368: /***/ ((__unused_webpack_module, exports) => { @@ -44009,17 +43624,20 @@ exports.NoopTextMapPropagator = void 0; /** * No-op implementations of {@link TextMapPropagator}. */ -class NoopTextMapPropagator { +var NoopTextMapPropagator = /** @class */ (function () { + function NoopTextMapPropagator() { + } /** Noop inject function does nothing */ - inject(_context, _carrier) { } + NoopTextMapPropagator.prototype.inject = function (_context, _carrier) { }; /** Noop extract function does nothing and returns the input context */ - extract(context, _carrier) { + NoopTextMapPropagator.prototype.extract = function (context, _carrier) { return context; - } - fields() { + }; + NoopTextMapPropagator.prototype.fields = function () { return []; - } -} + }; + return NoopTextMapPropagator; +}()); exports.NoopTextMapPropagator = NoopTextMapPropagator; //# sourceMappingURL=NoopTextMapPropagator.js.map @@ -44048,13 +43666,13 @@ exports.NoopTextMapPropagator = NoopTextMapPropagator; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; exports.defaultTextMapGetter = { - get(carrier, key) { + get: function (carrier, key) { if (carrier == null) { return undefined; } return carrier[key]; }, - keys(carrier) { + keys: function (carrier) { if (carrier == null) { return []; } @@ -44062,7 +43680,7 @@ exports.defaultTextMapGetter = { }, }; exports.defaultTextMapSetter = { - set(carrier, key, value) { + set: function (carrier, key, value) { if (carrier == null) { return; } @@ -44073,37 +43691,6 @@ exports.defaultTextMapSetter = { /***/ }), -/***/ 8989: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.trace = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const trace_1 = __nccwpck_require__(1539); -/** Entrypoint for trace API */ -exports.trace = trace_1.TraceAPI.getInstance(); -//# sourceMappingURL=trace-api.js.map - -/***/ }), - /***/ 1462: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -44126,49 +43713,51 @@ exports.trace = trace_1.TraceAPI.getInstance(); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; -const invalid_span_constants_1 = __nccwpck_require__(1760); +var invalid_span_constants_1 = __nccwpck_require__(1760); /** * The NonRecordingSpan is the default {@link Span} that is used when no Span * implementation is available. All operations are no-op including context * propagation. */ -class NonRecordingSpan { - constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { +var NonRecordingSpan = /** @class */ (function () { + function NonRecordingSpan(_spanContext) { + if (_spanContext === void 0) { _spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT; } this._spanContext = _spanContext; } // Returns a SpanContext. - spanContext() { + NonRecordingSpan.prototype.spanContext = function () { return this._spanContext; - } + }; // By default does nothing - setAttribute(_key, _value) { + NonRecordingSpan.prototype.setAttribute = function (_key, _value) { return this; - } + }; // By default does nothing - setAttributes(_attributes) { + NonRecordingSpan.prototype.setAttributes = function (_attributes) { return this; - } + }; // By default does nothing - addEvent(_name, _attributes) { + NonRecordingSpan.prototype.addEvent = function (_name, _attributes) { return this; - } + }; // By default does nothing - setStatus(_status) { + NonRecordingSpan.prototype.setStatus = function (_status) { return this; - } + }; // By default does nothing - updateName(_name) { + NonRecordingSpan.prototype.updateName = function (_name) { return this; - } + }; // By default does nothing - end(_endTime) { } + NonRecordingSpan.prototype.end = function (_endTime) { }; // isRecording always returns false for NonRecordingSpan. - isRecording() { + NonRecordingSpan.prototype.isRecording = function () { return false; - } + }; // By default does nothing - recordException(_exception, _time) { } -} + NonRecordingSpan.prototype.recordException = function (_exception, _time) { }; + return NonRecordingSpan; +}()); exports.NonRecordingSpan = NonRecordingSpan; //# sourceMappingURL=NonRecordingSpan.js.map @@ -44196,34 +43785,36 @@ exports.NonRecordingSpan = NonRecordingSpan; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; -const context_1 = __nccwpck_require__(7171); -const context_utils_1 = __nccwpck_require__(3326); -const NonRecordingSpan_1 = __nccwpck_require__(1462); -const spancontext_utils_1 = __nccwpck_require__(9745); -const contextApi = context_1.ContextAPI.getInstance(); +var context_1 = __nccwpck_require__(7171); +var context_utils_1 = __nccwpck_require__(3326); +var NonRecordingSpan_1 = __nccwpck_require__(1462); +var spancontext_utils_1 = __nccwpck_require__(9745); +var context = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. */ -class NoopTracer { +var NoopTracer = /** @class */ (function () { + function NoopTracer() { + } // startSpan starts a noop span. - startSpan(name, options, context = contextApi.active()) { - const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + NoopTracer.prototype.startSpan = function (name, options, context) { + var root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan_1.NonRecordingSpan(); } - const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); + var parentFromContext = context && context_utils_1.getSpanContext(context); if (isSpanContext(parentFromContext) && - (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { + spancontext_utils_1.isSpanContextValid(parentFromContext)) { return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); } else { return new NonRecordingSpan_1.NonRecordingSpan(); } - } - startActiveSpan(name, arg2, arg3, arg4) { - let opts; - let ctx; - let fn; + }; + NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { + var opts; + var ctx; + var fn; if (arguments.length < 2) { return; } @@ -44239,12 +43830,13 @@ class NoopTracer { ctx = arg3; fn = arg4; } - const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); - const span = this.startSpan(name, opts, parentContext); - const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); - return contextApi.with(contextWithSpanSet, fn, undefined, span); - } -} + var parentContext = ctx !== null && ctx !== void 0 ? ctx : context.active(); + var span = this.startSpan(name, opts, parentContext); + var contextWithSpanSet = context_utils_1.setSpan(parentContext, span); + return context.with(contextWithSpanSet, fn, undefined, span); + }; + return NoopTracer; +}()); exports.NoopTracer = NoopTracer; function isSpanContext(spanContext) { return (typeof spanContext === 'object' && @@ -44278,18 +43870,21 @@ function isSpanContext(spanContext) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; -const NoopTracer_1 = __nccwpck_require__(7606); +var NoopTracer_1 = __nccwpck_require__(7606); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. * * All operations are no-op. */ -class NoopTracerProvider { - getTracer(_name, _version, _options) { - return new NoopTracer_1.NoopTracer(); +var NoopTracerProvider = /** @class */ (function () { + function NoopTracerProvider() { } -} + NoopTracerProvider.prototype.getTracer = function (_name, _version) { + return new NoopTracer_1.NoopTracer(); + }; + return NoopTracerProvider; +}()); exports.NoopTracerProvider = NoopTracerProvider; //# sourceMappingURL=NoopTracerProvider.js.map @@ -44317,41 +43912,41 @@ exports.NoopTracerProvider = NoopTracerProvider; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; -const NoopTracer_1 = __nccwpck_require__(7606); -const NOOP_TRACER = new NoopTracer_1.NoopTracer(); +var NoopTracer_1 = __nccwpck_require__(7606); +var NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider */ -class ProxyTracer { - constructor(_provider, name, version, options) { +var ProxyTracer = /** @class */ (function () { + function ProxyTracer(_provider, name, version) { this._provider = _provider; this.name = name; this.version = version; - this.options = options; } - startSpan(name, options, context) { + ProxyTracer.prototype.startSpan = function (name, options, context) { return this._getTracer().startSpan(name, options, context); - } - startActiveSpan(_name, _options, _context, _fn) { - const tracer = this._getTracer(); + }; + ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) { + var tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); - } + }; /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. */ - _getTracer() { + ProxyTracer.prototype._getTracer = function () { if (this._delegate) { return this._delegate; } - const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + var tracer = this._provider.getDelegateTracer(this.name, this.version); if (!tracer) { return NOOP_TRACER; } this._delegate = tracer; return this._delegate; - } -} + }; + return ProxyTracer; +}()); exports.ProxyTracer = ProxyTracer; //# sourceMappingURL=ProxyTracer.js.map @@ -44379,9 +43974,9 @@ exports.ProxyTracer = ProxyTracer; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; -const ProxyTracer_1 = __nccwpck_require__(3503); -const NoopTracerProvider_1 = __nccwpck_require__(3259); -const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); +var ProxyTracer_1 = __nccwpck_require__(3503); +var NoopTracerProvider_1 = __nccwpck_require__(3259); +var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. * @@ -44390,34 +43985,62 @@ const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); * When a delegate is set after tracers have already been provided, * all tracers already provided will use the provided delegate implementation. */ -class ProxyTracerProvider { +var ProxyTracerProvider = /** @class */ (function () { + function ProxyTracerProvider() { + } /** * Get a {@link ProxyTracer} */ - getTracer(name, version, options) { + ProxyTracerProvider.prototype.getTracer = function (name, version) { var _a; - return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); - } - getDelegate() { + return ((_a = this.getDelegateTracer(name, version)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version)); + }; + ProxyTracerProvider.prototype.getDelegate = function () { var _a; return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; - } + }; /** * Set the delegate tracer provider */ - setDelegate(delegate) { + ProxyTracerProvider.prototype.setDelegate = function (delegate) { this._delegate = delegate; - } - getDelegateTracer(name, version, options) { + }; + ProxyTracerProvider.prototype.getDelegateTracer = function (name, version) { var _a; - return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); - } -} + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version); + }; + return ProxyTracerProvider; +}()); exports.ProxyTracerProvider = ProxyTracerProvider; //# sourceMappingURL=ProxyTracerProvider.js.map /***/ }), +/***/ 9671: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=Sampler.js.map + +/***/ }), + /***/ 3209: /***/ ((__unused_webpack_module, exports) => { @@ -44441,7 +44064,6 @@ exports.ProxyTracerProvider = ProxyTracerProvider; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SamplingDecision = void 0; /** - * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. * A sampling decision that determines how a {@link Span} will be recorded * and collected. */ @@ -44467,6 +44089,56 @@ var SamplingDecision; /***/ }), +/***/ 955: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=SpanOptions.js.map + +/***/ }), + +/***/ 7492: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=attributes.js.map + +/***/ }), + /***/ 3326: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -44488,14 +44160,13 @@ var SamplingDecision; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; -const context_1 = __nccwpck_require__(8242); -const NonRecordingSpan_1 = __nccwpck_require__(1462); -const context_2 = __nccwpck_require__(7171); +exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0; +var context_1 = __nccwpck_require__(8242); +var NonRecordingSpan_1 = __nccwpck_require__(1462); /** * span key */ -const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); +var SPAN_KEY = context_1.createContextKey('OpenTelemetry Context Key SPAN'); /** * Return the span if one exists * @@ -44505,13 +44176,6 @@ function getSpan(context) { return context.getValue(SPAN_KEY) || undefined; } exports.getSpan = getSpan; -/** - * Gets the span from the current context, if one exists. - */ -function getActiveSpan() { - return getSpan(context_2.ContextAPI.getInstance().active()); -} -exports.getActiveSpan = getActiveSpan; /** * Set the span on a context * @@ -44556,7 +44220,7 @@ exports.getSpanContext = getSpanContext; /***/ }), -/***/ 2110: +/***/ 1760: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44577,96 +44241,20 @@ exports.getSpanContext = getSpanContext; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TraceStateImpl = void 0; -const tracestate_validators_1 = __nccwpck_require__(4864); -const MAX_TRACE_STATE_ITEMS = 32; -const MAX_TRACE_STATE_LEN = 512; -const LIST_MEMBERS_SEPARATOR = ','; -const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; -/** - * TraceState must be a class and not a simple object type because of the spec - * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). - * - * Here is the list of allowed mutations: - * - New key-value pair should be added into the beginning of the list - * - The value of any key can be updated. Modified keys MUST be moved to the - * beginning of the list. - */ -class TraceStateImpl { - constructor(rawTraceState) { - this._internalState = new Map(); - if (rawTraceState) - this._parse(rawTraceState); - } - set(key, value) { - // TODO: Benchmark the different approaches(map vs list) and - // use the faster one. - const traceState = this._clone(); - if (traceState._internalState.has(key)) { - traceState._internalState.delete(key); - } - traceState._internalState.set(key, value); - return traceState; - } - unset(key) { - const traceState = this._clone(); - traceState._internalState.delete(key); - return traceState; - } - get(key) { - return this._internalState.get(key); - } - serialize() { - return this._keys() - .reduce((agg, key) => { - agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); - return agg; - }, []) - .join(LIST_MEMBERS_SEPARATOR); - } - _parse(rawTraceState) { - if (rawTraceState.length > MAX_TRACE_STATE_LEN) - return; - this._internalState = rawTraceState - .split(LIST_MEMBERS_SEPARATOR) - .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning - .reduce((agg, part) => { - const listMember = part.trim(); // Optional Whitespace (OWS) handling - const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); - if (i !== -1) { - const key = listMember.slice(0, i); - const value = listMember.slice(i + 1, part.length); - if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { - agg.set(key, value); - } - else { - // TODO: Consider to add warning log - } - } - return agg; - }, new Map()); - // Because of the reverse() requirement, trunc must be done after map is created - if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { - this._internalState = new Map(Array.from(this._internalState.entries()) - .reverse() // Use reverse same as original tracestate parse chain - .slice(0, MAX_TRACE_STATE_ITEMS)); - } - } - _keys() { - return Array.from(this._internalState.keys()).reverse(); - } - _clone() { - const traceState = new TraceStateImpl(); - traceState._internalState = new Map(this._internalState); - return traceState; - } -} -exports.TraceStateImpl = TraceStateImpl; -//# sourceMappingURL=tracestate-impl.js.map +exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +var trace_flags_1 = __nccwpck_require__(6905); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map /***/ }), -/***/ 4864: +/***/ 4023: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -44687,40 +44275,12 @@ exports.TraceStateImpl = TraceStateImpl; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateValue = exports.validateKey = void 0; -const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; -const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; -const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; -const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); -const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; -const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; -/** - * Key is opaque string up to 256 characters printable. It MUST begin with a - * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, - * underscores _, dashes -, asterisks *, and forward slashes /. - * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the - * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. - * see https://www.w3.org/TR/trace-context/#key - */ -function validateKey(key) { - return VALID_KEY_REGEX.test(key); -} -exports.validateKey = validateKey; -/** - * Value is opaque string up to 256 characters printable ASCII RFC0020 - * characters (i.e., the range 0x20 to 0x7E) except comma , and =. - */ -function validateValue(value) { - return (VALID_VALUE_BASE_REGEX.test(value) && - !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); -} -exports.validateValue = validateValue; -//# sourceMappingURL=tracestate-validators.js.map +//# sourceMappingURL=link.js.map /***/ }), -/***/ 2615: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4416: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -44740,18 +44300,12 @@ exports.validateValue = validateValue; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createTraceState = void 0; -const tracestate_impl_1 = __nccwpck_require__(2110); -function createTraceState(rawTraceState) { - return new tracestate_impl_1.TraceStateImpl(rawTraceState); -} -exports.createTraceState = createTraceState; -//# sourceMappingURL=utils.js.map +//# sourceMappingURL=span.js.map /***/ }), -/***/ 1760: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5769: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -44771,16 +44325,7 @@ exports.createTraceState = createTraceState; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -const trace_flags_1 = __nccwpck_require__(6905); -exports.INVALID_SPANID = '0000000000000000'; -exports.INVALID_TRACEID = '00000000000000000000000000000000'; -exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, -}; -//# sourceMappingURL=invalid-span-constants.js.map +//# sourceMappingURL=span_context.js.map /***/ }), @@ -44859,10 +44404,10 @@ exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = e * See the License for the specific language governing permissions and * limitations under the License. */ -const invalid_span_constants_1 = __nccwpck_require__(1760); -const NonRecordingSpan_1 = __nccwpck_require__(1462); -const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; -const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +var invalid_span_constants_1 = __nccwpck_require__(1760); +var NonRecordingSpan_1 = __nccwpck_require__(1462); +var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; } @@ -44956,6 +44501,81 @@ var TraceFlags; /***/ }), +/***/ 8384: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=trace_state.js.map + +/***/ }), + +/***/ 3168: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=tracer.js.map + +/***/ }), + +/***/ 891: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=tracer_provider.js.map + +/***/ }), + /***/ 8996: /***/ ((__unused_webpack_module, exports) => { @@ -44979,7 +44599,7 @@ var TraceFlags; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.4.1'; +exports.VERSION = '1.0.4'; //# sourceMappingURL=version.js.map /***/ }), @@ -59628,7 +59248,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerVersion = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerVersion = exports.getPackageManagerCommandOutput = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -59671,8 +59291,10 @@ const getPackageManagerWorkingDir = () => { return cacheDependencyPath ? path_1.default.dirname(cacheDependencyPath) : null; }; exports.getPackageManagerWorkingDir = getPackageManagerWorkingDir; +const getPackageManagerCommandOutput = (command) => exports.getCommandOutput(command, exports.getPackageManagerWorkingDir()); +exports.getPackageManagerCommandOutput = getPackageManagerCommandOutput; const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`, exports.getPackageManagerWorkingDir()); + const stdOut = yield exports.getPackageManagerCommandOutput(`${packageManager} ${command}`); if (!stdOut) { throw new Error(`Could not retrieve version of ${packageManager}`); } @@ -59702,7 +59324,7 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void }); exports.getPackageManagerInfo = getPackageManagerInfo; const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand, exports.getPackageManagerWorkingDir()); + const stdOut = yield exports.getPackageManagerCommandOutput(packageManagerInfo.getCacheFolderCommand); if (!stdOut) { throw new Error(`Could not get cache folder path for ${packageManager}`); } diff --git a/dist/setup/index.js b/dist/setup/index.js index 6e74066e1..bb5ac4647 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -9630,18 +9630,19 @@ function _getGlobal(key, defaultValue) { /***/ }), /***/ 2557: -/***/ ((__unused_webpack_module, exports) => { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib = __nccwpck_require__(9268); + // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/// -const listenersMap = new WeakMap(); -const abortedMap = new WeakMap(); +var listenersMap = new WeakMap(); +var abortedMap = new WeakMap(); /** * An aborter instance implements AbortSignal interface, can abort HTTP requests. * @@ -9655,8 +9656,8 @@ const abortedMap = new WeakMap(); * await doAsyncWork(AbortSignal.none); * ``` */ -class AbortSignal { - constructor() { +var AbortSignal = /** @class */ (function () { + function AbortSignal() { /** * onabort event listener. */ @@ -9664,65 +9665,74 @@ class AbortSignal { listenersMap.set(this, []); abortedMap.set(this, false); } - /** - * Status of whether aborted or not. - * - * @readonly - */ - get aborted() { - if (!abortedMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - return abortedMap.get(this); - } - /** - * Creates a new AbortSignal instance that will never be aborted. - * - * @readonly - */ - static get none() { - return new AbortSignal(); - } + Object.defineProperty(AbortSignal.prototype, "aborted", { + /** + * Status of whether aborted or not. + * + * @readonly + */ + get: function () { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + return abortedMap.get(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbortSignal, "none", { + /** + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + */ + get: function () { + return new AbortSignal(); + }, + enumerable: false, + configurable: true + }); /** * Added new "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be added */ - addEventListener( + AbortSignal.prototype.addEventListener = function ( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - const listeners = listenersMap.get(this); + var listeners = listenersMap.get(this); listeners.push(listener); - } + }; /** * Remove "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be removed */ - removeEventListener( + AbortSignal.prototype.removeEventListener = function ( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - const listeners = listenersMap.get(this); - const index = listeners.indexOf(listener); + var listeners = listenersMap.get(this); + var index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } - } + }; /** * Dispatches a synthetic event to the AbortSignal. */ - dispatchEvent(_event) { + AbortSignal.prototype.dispatchEvent = function (_event) { throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); - } -} + }; + return AbortSignal; +}()); /** * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. * Will try to trigger abort event for all linked AbortSignal nodes. @@ -9740,12 +9750,12 @@ function abortSignal(signal) { if (signal.onabort) { signal.onabort.call(signal); } - const listeners = listenersMap.get(signal); + var listeners = listenersMap.get(signal); if (listeners) { // Create a copy of listeners so mutations to the array // (e.g. via removeListener calls) don't affect the listeners // we invoke. - listeners.slice().forEach((listener) => { + listeners.slice().forEach(function (listener) { listener.call(signal, { type: "abort" }); }); } @@ -9771,12 +9781,15 @@ function abortSignal(signal) { * } * ``` */ -class AbortError extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; +var AbortError = /** @class */ (function (_super) { + tslib.__extends(AbortError, _super); + function AbortError(message) { + var _this = _super.call(this, message) || this; + _this.name = "AbortError"; + return _this; } -} + return AbortError; +}(Error)); /** * An AbortController provides an AbortSignal and the associated controls to signal * that an asynchronous operation should be aborted. @@ -9811,9 +9824,10 @@ class AbortError extends Error { * await doAsyncWork(aborter.withTimeout(25 * 1000)); * ``` */ -class AbortController { +var AbortController = /** @class */ (function () { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - constructor(parentSignals) { + function AbortController(parentSignals) { + var _this = this; this._signal = new AbortSignal(); if (!parentSignals) { return; @@ -9823,7 +9837,8 @@ class AbortController { // eslint-disable-next-line prefer-rest-params parentSignals = arguments; } - for (const parentSignal of parentSignals) { + for (var _i = 0, parentSignals_1 = parentSignals; _i < parentSignals_1.length; _i++) { + var parentSignal = parentSignals_1[_i]; // if the parent signal has already had abort() called, // then call abort on this signal as well. if (parentSignal.aborted) { @@ -9831,42 +9846,47 @@ class AbortController { } else { // when the parent signal aborts, this signal should as well. - parentSignal.addEventListener("abort", () => { - this.abort(); + parentSignal.addEventListener("abort", function () { + _this.abort(); }); } } } - /** - * The AbortSignal associated with this controller that will signal aborted - * when the abort method is called on this controller. - * - * @readonly - */ - get signal() { - return this._signal; - } + Object.defineProperty(AbortController.prototype, "signal", { + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + get: function () { + return this._signal; + }, + enumerable: false, + configurable: true + }); /** * Signal that any operations passed this controller's associated abort signal * to cancel any remaining work and throw an `AbortError`. */ - abort() { + AbortController.prototype.abort = function () { abortSignal(this._signal); - } + }; /** * Creates a new AbortSignal instance that will abort after the provided ms. * @param ms - Elapsed time in milliseconds to trigger an abort. */ - static timeout(ms) { - const signal = new AbortSignal(); - const timer = setTimeout(abortSignal, ms, signal); + AbortController.timeout = function (ms) { + var signal = new AbortSignal(); + var timer = setTimeout(abortSignal, ms, signal); // Prevent the active Timer from keeping the Node.js event loop active. if (typeof timer.unref === "function") { timer.unref(); } return signal; - } -} + }; + return AbortController; +}()); exports.AbortController = AbortController; exports.AbortError = AbortError; @@ -9874,6 +9894,333 @@ exports.AbortSignal = AbortSignal; //# sourceMappingURL=index.js.map +/***/ }), + +/***/ 9268: +/***/ ((module) => { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), + +/***/ 2356: +/***/ (() => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +if (typeof Symbol === undefined || !Symbol.asyncIterator) { + Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); +} +//# sourceMappingURL=index.js.map + /***/ }), /***/ 9645: @@ -17136,689 +17483,6 @@ exports["default"] = _default; Object.defineProperty(exports, "__esModule", ({ value: true })); var logger$1 = __nccwpck_require__(3233); -var abortController = __nccwpck_require__(2557); -var coreUtil = __nccwpck_require__(1333); - -// Copyright (c) Microsoft Corporation. -/** - * The `@azure/logger` configuration for this package. - * @internal - */ -const logger = logger$1.createClientLogger("core-lro"); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * The default time interval to wait before sending the next polling request. - */ -const POLL_INTERVAL_IN_MS = 2000; -/** - * The closed set of terminal states. - */ -const terminalStates = ["succeeded", "canceled", "failed"]; - -// Copyright (c) Microsoft Corporation. -/** - * Deserializes the state - */ -function deserializeState(serializedState) { - try { - return JSON.parse(serializedState).state; - } - catch (e) { - throw new Error(`Unable to deserialize input state: ${serializedState}`); - } -} -function setStateError(inputs) { - const { state, stateProxy, isOperationError } = inputs; - return (error) => { - if (isOperationError(error)) { - stateProxy.setError(state, error); - stateProxy.setFailed(state); - } - throw error; - }; -} -function processOperationStatus(result) { - const { state, stateProxy, status, isDone, processResult, response, setErrorAsResult } = result; - switch (status) { - case "succeeded": { - stateProxy.setSucceeded(state); - break; - } - case "failed": { - stateProxy.setError(state, new Error(`The long-running operation has failed`)); - stateProxy.setFailed(state); - break; - } - case "canceled": { - stateProxy.setCanceled(state); - break; - } - } - if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || - (isDone === undefined && - ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) { - stateProxy.setResult(state, buildResult({ - response, - state, - processResult, - })); - } -} -function buildResult(inputs) { - const { processResult, response, state } = inputs; - return processResult ? processResult(response, state) : response; -} -/** - * Initiates the long-running operation. - */ -async function initOperation(inputs) { - const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs; - const { operationLocation, resourceLocation, metadata, response } = await init(); - if (operationLocation) - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); - const config = { - metadata, - operationLocation, - resourceLocation, - }; - logger.verbose(`LRO: Operation description:`, config); - const state = stateProxy.initState(config); - const status = getOperationStatus({ response, state, operationLocation }); - processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult }); - return state; -} -async function pollOperationHelper(inputs) { - const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs; - const response = await poll(operationLocation, options).catch(setStateError({ - state, - stateProxy, - isOperationError, - })); - const status = getOperationStatus(response, state); - logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); - if (status === "succeeded") { - const resourceLocation = getResourceLocation(response, state); - if (resourceLocation !== undefined) { - return { - response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })), - status, - }; - } - } - return { response, status }; -} -/** Polls the long-running operation. */ -async function pollOperation(inputs) { - const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, updateState, setDelay, isDone, setErrorAsResult, } = inputs; - const { operationLocation } = state.config; - if (operationLocation !== undefined) { - const { response, status } = await pollOperationHelper({ - poll, - getOperationStatus, - state, - stateProxy, - operationLocation, - getResourceLocation, - isOperationError, - options, - }); - processOperationStatus({ - status, - response, - state, - stateProxy, - isDone, - processResult, - setErrorAsResult, - }); - if (!terminalStates.includes(status)) { - const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); - if (intervalInMs) - setDelay(intervalInMs); - const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state); - if (location !== undefined) { - const isUpdated = operationLocation !== location; - state.config.operationLocation = location; - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated); - } - else - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); - } - updateState === null || updateState === void 0 ? void 0 : updateState(state, response); - } -} - -// Copyright (c) Microsoft Corporation. -function getOperationLocationPollingUrl(inputs) { - const { azureAsyncOperation, operationLocation } = inputs; - return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; -} -function getLocationHeader(rawResponse) { - return rawResponse.headers["location"]; -} -function getOperationLocationHeader(rawResponse) { - return rawResponse.headers["operation-location"]; -} -function getAzureAsyncOperationHeader(rawResponse) { - return rawResponse.headers["azure-asyncoperation"]; -} -function findResourceLocation(inputs) { - const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; - switch (requestMethod) { - case "PUT": { - return requestPath; - } - case "DELETE": { - return undefined; - } - default: { - switch (resourceLocationConfig) { - case "azure-async-operation": { - return undefined; - } - case "original-uri": { - return requestPath; - } - case "location": - default: { - return location; - } - } - } - } -} -function inferLroMode(inputs) { - const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs; - const operationLocation = getOperationLocationHeader(rawResponse); - const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse); - const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation }); - const location = getLocationHeader(rawResponse); - const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase(); - if (pollingUrl !== undefined) { - return { - mode: "OperationLocation", - operationLocation: pollingUrl, - resourceLocation: findResourceLocation({ - requestMethod: normalizedRequestMethod, - location, - requestPath, - resourceLocationConfig, - }), - }; - } - else if (location !== undefined) { - return { - mode: "ResourceLocation", - operationLocation: location, - }; - } - else if (normalizedRequestMethod === "PUT" && requestPath) { - return { - mode: "Body", - operationLocation: requestPath, - }; - } - else { - return undefined; - } -} -function transformStatus(inputs) { - const { status, statusCode } = inputs; - if (typeof status !== "string" && status !== undefined) { - throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`); - } - switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) { - case undefined: - return toOperationStatus(statusCode); - case "succeeded": - return "succeeded"; - case "failed": - return "failed"; - case "running": - case "accepted": - case "started": - case "canceling": - case "cancelling": - return "running"; - case "canceled": - case "cancelled": - return "canceled"; - default: { - logger.verbose(`LRO: unrecognized operation status: ${status}`); - return status; - } - } -} -function getStatus(rawResponse) { - var _a; - const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - return transformStatus({ status, statusCode: rawResponse.statusCode }); -} -function getProvisioningState(rawResponse) { - var _a, _b; - const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; - return transformStatus({ status, statusCode: rawResponse.statusCode }); -} -function toOperationStatus(statusCode) { - if (statusCode === 202) { - return "running"; - } - else if (statusCode < 300) { - return "succeeded"; - } - else { - return "failed"; - } -} -function parseRetryAfter({ rawResponse }) { - const retryAfter = rawResponse.headers["retry-after"]; - if (retryAfter !== undefined) { - // Retry-After header value is either in HTTP date format, or in seconds - const retryAfterInSeconds = parseInt(retryAfter); - return isNaN(retryAfterInSeconds) - ? calculatePollingIntervalFromDate(new Date(retryAfter)) - : retryAfterInSeconds * 1000; - } - return undefined; -} -function calculatePollingIntervalFromDate(retryAfterDate) { - const timeNow = Math.floor(new Date().getTime()); - const retryAfterTime = retryAfterDate.getTime(); - if (timeNow < retryAfterTime) { - return retryAfterTime - timeNow; - } - return undefined; -} -function getStatusFromInitialResponse(inputs) { - const { response, state, operationLocation } = inputs; - function helper() { - var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case undefined: - return toOperationStatus(response.rawResponse.statusCode); - case "Body": - return getOperationStatus(response, state); - default: - return "running"; - } - } - const status = helper(); - return status === "running" && operationLocation === undefined ? "succeeded" : status; -} -/** - * Initiates the long-running operation. - */ -async function initHttpOperation(inputs) { - const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs; - return initOperation({ - init: async () => { - const response = await lro.sendInitialRequest(); - const config = inferLroMode({ - rawResponse: response.rawResponse, - requestPath: lro.requestPath, - requestMethod: lro.requestMethod, - resourceLocationConfig, - }); - return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); - }, - stateProxy, - processResult: processResult - ? ({ flatResponse }, state) => processResult(flatResponse, state) - : ({ flatResponse }) => flatResponse, - getOperationStatus: getStatusFromInitialResponse, - setErrorAsResult, - }); -} -function getOperationLocation({ rawResponse }, state) { - var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case "OperationLocation": { - return getOperationLocationPollingUrl({ - operationLocation: getOperationLocationHeader(rawResponse), - azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse), - }); - } - case "ResourceLocation": { - return getLocationHeader(rawResponse); - } - case "Body": - default: { - return undefined; - } - } -} -function getOperationStatus({ rawResponse }, state) { - var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case "OperationLocation": { - return getStatus(rawResponse); - } - case "ResourceLocation": { - return toOperationStatus(rawResponse.statusCode); - } - case "Body": { - return getProvisioningState(rawResponse); - } - default: - throw new Error(`Internal error: Unexpected operation mode: ${mode}`); - } -} -function getResourceLocation({ flatResponse }, state) { - if (typeof flatResponse === "object") { - const resourceLocation = flatResponse.resourceLocation; - if (resourceLocation !== undefined) { - state.config.resourceLocation = resourceLocation; - } - } - return state.config.resourceLocation; -} -function isOperationError(e) { - return e.name === "RestError"; -} -/** Polls the long-running operation. */ -async function pollHttpOperation(inputs) { - const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs; - return pollOperation({ - state, - stateProxy, - setDelay, - processResult: processResult - ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState) - : ({ flatResponse }) => flatResponse, - updateState, - getPollingInterval: parseRetryAfter, - getOperationLocation, - getOperationStatus, - isOperationError, - getResourceLocation, - options, - /** - * The expansion here is intentional because `lro` could be an object that - * references an inner this, so we need to preserve a reference to it. - */ - poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions), - setErrorAsResult, - }); -} - -// Copyright (c) Microsoft Corporation. -const createStateProxy$1 = () => ({ - /** - * The state at this point is created to be of type OperationState. - * It will be updated later to be of type TState when the - * customer-provided callback, `updateState`, is called during polling. - */ - initState: (config) => ({ status: "running", config }), - setCanceled: (state) => (state.status = "canceled"), - setError: (state, error) => (state.error = error), - setResult: (state, result) => (state.result = result), - setRunning: (state) => (state.status = "running"), - setSucceeded: (state) => (state.status = "succeeded"), - setFailed: (state) => (state.status = "failed"), - getError: (state) => state.error, - getResult: (state) => state.result, - isCanceled: (state) => state.status === "canceled", - isFailed: (state) => state.status === "failed", - isRunning: (state) => state.status === "running", - isSucceeded: (state) => state.status === "succeeded", -}); -/** - * Returns a poller factory. - */ -function buildCreatePoller(inputs) { - const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, resolveOnUnsuccessful, } = inputs; - return async ({ init, poll }, options) => { - const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {}; - const stateProxy = createStateProxy$1(); - const withOperationLocation = withOperationLocationCallback - ? (() => { - let called = false; - return (operationLocation, isUpdated) => { - if (isUpdated) - withOperationLocationCallback(operationLocation); - else if (!called) - withOperationLocationCallback(operationLocation); - called = true; - }; - })() - : undefined; - const state = restoreFrom - ? deserializeState(restoreFrom) - : await initOperation({ - init, - stateProxy, - processResult, - getOperationStatus: getStatusFromInitialResponse, - withOperationLocation, - setErrorAsResult: !resolveOnUnsuccessful, - }); - let resultPromise; - const abortController$1 = new abortController.AbortController(); - const handlers = new Map(); - const handleProgressEvents = async () => handlers.forEach((h) => h(state)); - const cancelErrMsg = "Operation was canceled"; - let currentPollIntervalInMs = intervalInMs; - const poller = { - getOperationState: () => state, - getResult: () => state.result, - isDone: () => ["succeeded", "failed", "canceled"].includes(state.status), - isStopped: () => resultPromise === undefined, - stopPolling: () => { - abortController$1.abort(); - }, - toString: () => JSON.stringify({ - state, - }), - onProgress: (callback) => { - const s = Symbol(); - handlers.set(s, callback); - return () => handlers.delete(s); - }, - pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => { - const { abortSignal: inputAbortSignal } = pollOptions || {}; - const { signal: abortSignal } = inputAbortSignal - ? new abortController.AbortController([inputAbortSignal, abortController$1.signal]) - : abortController$1; - if (!poller.isDone()) { - await poller.poll({ abortSignal }); - while (!poller.isDone()) { - await coreUtil.delay(currentPollIntervalInMs, { abortSignal }); - await poller.poll({ abortSignal }); - } - } - if (resolveOnUnsuccessful) { - return poller.getResult(); - } - else { - switch (state.status) { - case "succeeded": - return poller.getResult(); - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - case "notStarted": - case "running": - throw new Error(`Polling completed without succeeding or failing`); - } - } - })().finally(() => { - resultPromise = undefined; - }))), - async poll(pollOptions) { - if (resolveOnUnsuccessful) { - if (poller.isDone()) - return; - } - else { - switch (state.status) { - case "succeeded": - return; - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - } - } - await pollOperation({ - poll, - state, - stateProxy, - getOperationLocation, - isOperationError, - withOperationLocation, - getPollingInterval, - getOperationStatus: getStatusFromPollResponse, - getResourceLocation, - processResult, - updateState, - options: pollOptions, - setDelay: (pollIntervalInMs) => { - currentPollIntervalInMs = pollIntervalInMs; - }, - setErrorAsResult: !resolveOnUnsuccessful, - }); - await handleProgressEvents(); - if (!resolveOnUnsuccessful) { - switch (state.status) { - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - } - } - }, - }; - return poller; - }; -} - -// Copyright (c) Microsoft Corporation. -/** - * Creates a poller that can be used to poll a long-running operation. - * @param lro - Description of the long-running operation - * @param options - options to configure the poller - * @returns an initialized poller - */ -async function createHttpPoller(lro, options) { - const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {}; - return buildCreatePoller({ - getStatusFromInitialResponse, - getStatusFromPollResponse: getOperationStatus, - isOperationError, - getOperationLocation, - getResourceLocation, - getPollingInterval: parseRetryAfter, - resolveOnUnsuccessful, - })({ - init: async () => { - const response = await lro.sendInitialRequest(); - const config = inferLroMode({ - rawResponse: response.rawResponse, - requestPath: lro.requestPath, - requestMethod: lro.requestMethod, - resourceLocationConfig, - }); - return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); - }, - poll: lro.sendPollRequest, - }, { - intervalInMs, - withOperationLocation, - restoreFrom, - updateState, - processResult: processResult - ? ({ flatResponse }, state) => processResult(flatResponse, state) - : ({ flatResponse }) => flatResponse, - }); -} - -// Copyright (c) Microsoft Corporation. -const createStateProxy = () => ({ - initState: (config) => ({ config, isStarted: true }), - setCanceled: (state) => (state.isCancelled = true), - setError: (state, error) => (state.error = error), - setResult: (state, result) => (state.result = result), - setRunning: (state) => (state.isStarted = true), - setSucceeded: (state) => (state.isCompleted = true), - setFailed: () => { - /** empty body */ - }, - getError: (state) => state.error, - getResult: (state) => state.result, - isCanceled: (state) => !!state.isCancelled, - isFailed: (state) => !!state.error, - isRunning: (state) => !!state.isStarted, - isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error), -}); -class GenericPollOperation { - constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) { - this.state = state; - this.lro = lro; - this.setErrorAsResult = setErrorAsResult; - this.lroResourceLocationConfig = lroResourceLocationConfig; - this.processResult = processResult; - this.updateState = updateState; - this.isDone = isDone; - } - setPollerConfig(pollerConfig) { - this.pollerConfig = pollerConfig; - } - async update(options) { - var _a; - const stateProxy = createStateProxy(); - if (!this.state.isStarted) { - this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({ - lro: this.lro, - stateProxy, - resourceLocationConfig: this.lroResourceLocationConfig, - processResult: this.processResult, - setErrorAsResult: this.setErrorAsResult, - }))); - } - const updateState = this.updateState; - const isDone = this.isDone; - if (!this.state.isCompleted && this.state.error === undefined) { - await pollHttpOperation({ - lro: this.lro, - state: this.state, - stateProxy, - processResult: this.processResult, - updateState: updateState - ? (state, { rawResponse }) => updateState(state, rawResponse) - : undefined, - isDone: isDone - ? ({ flatResponse }, state) => isDone(flatResponse, state) - : undefined, - options, - setDelay: (intervalInMs) => { - this.pollerConfig.intervalInMs = intervalInMs; - }, - setErrorAsResult: this.setErrorAsResult, - }); - } - (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state); - return this; - } - async cancel() { - logger.error("`cancelOperation` is deprecated because it wasn't implemented"); - return this; - } - /** - * Serializes the Poller operation. - */ - toString() { - return JSON.stringify({ - state: this.state, - }); - } -} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -17834,8 +17498,8 @@ class PollerStoppedError extends Error { } } /** - * When the operation is cancelled, the poller will be rejected with an instance - * of the PollerCancelledError. + * When a poller is cancelled through the `cancelOperation` method, + * the poller will be rejected with an instance of the PollerCancelledError. */ class PollerCancelledError extends Error { constructor(message) { @@ -17973,8 +17637,6 @@ class Poller { * @param operation - Must contain the basic properties of `PollOperation`. */ constructor(operation) { - /** controls whether to throw an error if the operation failed or was canceled. */ - this.resolveOnUnsuccessful = false; this.stopped = true; this.pollProgressCallbacks = []; this.operation = operation; @@ -17993,12 +17655,12 @@ class Poller { * Starts a loop that will break only if the poller is done * or if the poller is stopped. */ - async startPolling(pollOptions = {}) { + async startPolling() { if (this.stopped) { this.stopped = false; } while (!this.isStopped() && !this.isDone()) { - await this.poll(pollOptions); + await this.poll(); await this.delay(); } } @@ -18011,13 +17673,29 @@ class Poller { * @param options - Optional properties passed to the operation's update method. */ async pollOnce(options = {}) { - if (!this.isDone()) { - this.operation = await this.operation.update({ - abortSignal: options.abortSignal, - fireProgress: this.fireProgress.bind(this), - }); + try { + if (!this.isDone()) { + this.operation = await this.operation.update({ + abortSignal: options.abortSignal, + fireProgress: this.fireProgress.bind(this), + }); + if (this.isDone() && this.resolve) { + // If the poller has finished polling, this means we now have a result. + // However, it can be the case that TResult is instantiated to void, so + // we are not expecting a result anyway. To assert that we might not + // have a result eventually after finishing polling, we cast the result + // to TResult. + this.resolve(this.operation.state.result); + } + } + } + catch (e) { + this.operation.state.error = e; + if (this.reject) { + this.reject(e); + } + throw e; } - this.processUpdatedState(); } /** * fireProgress calls the functions passed in via onProgress the method of the poller. @@ -18033,10 +17711,14 @@ class Poller { } } /** - * Invokes the underlying operation's cancel method. + * Invokes the underlying operation's cancel method, and rejects the + * pollUntilDone promise. */ async cancelOnce(options = {}) { this.operation = await this.operation.cancel(options); + if (this.reject) { + this.reject(new PollerCancelledError("Poller cancelled")); + } } /** * Returns a promise that will resolve once a single polling request finishes. @@ -18056,41 +17738,13 @@ class Poller { } return this.pollOncePromise; } - processUpdatedState() { - if (this.operation.state.error) { - this.stopped = true; - if (!this.resolveOnUnsuccessful) { - this.reject(this.operation.state.error); - throw this.operation.state.error; - } - } - if (this.operation.state.isCancelled) { - this.stopped = true; - if (!this.resolveOnUnsuccessful) { - const error = new PollerCancelledError("Operation was canceled"); - this.reject(error); - throw error; - } - } - if (this.isDone() && this.resolve) { - // If the poller has finished polling, this means we now have a result. - // However, it can be the case that TResult is instantiated to void, so - // we are not expecting a result anyway. To assert that we might not - // have a result eventually after finishing polling, we cast the result - // to TResult. - this.resolve(this.getResult()); - } - } /** * Returns a promise that will resolve once the underlying operation is completed. */ - async pollUntilDone(pollOptions = {}) { + async pollUntilDone() { if (this.stopped) { - this.startPolling(pollOptions).catch(this.reject); + this.startPolling().catch(this.reject); } - // This is needed because the state could have been updated by - // `cancelOperation`, e.g. the operation is canceled or an error occurred. - this.processUpdatedState(); return this.promise; } /** @@ -18139,6 +17793,9 @@ class Poller { * @param options - Optional properties passed to the operation's update method. */ cancelOperation(options = {}) { + if (!this.stopped) { + this.stopped = true; + } if (!this.cancelPromise) { this.cancelPromise = this.cancelOnce(options); } @@ -18218,18 +17875,344 @@ class Poller { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Detects where the continuation token is and returns it. Notice that azure-asyncoperation + * must be checked first before the other location headers because there are scenarios + * where both azure-asyncoperation and location could be present in the same response but + * azure-asyncoperation should be the one to use for polling. + */ +function getPollingUrl(rawResponse, defaultPath) { + var _a, _b, _c; + return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getOperationLocation(rawResponse)) !== null && _b !== void 0 ? _b : getLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath); +} +function getLocation(rawResponse) { + return rawResponse.headers["location"]; +} +function getOperationLocation(rawResponse) { + return rawResponse.headers["operation-location"]; +} +function getAzureAsyncOperation(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; +} +function findResourceLocation(requestMethod, rawResponse, requestPath) { + switch (requestMethod) { + case "PUT": { + return requestPath; + } + case "POST": + case "PATCH": { + return getLocation(rawResponse); + } + default: { + return undefined; + } + } +} +function inferLroMode(requestPath, requestMethod, rawResponse) { + if (getAzureAsyncOperation(rawResponse) !== undefined || + getOperationLocation(rawResponse) !== undefined) { + return { + mode: "Location", + resourceLocation: findResourceLocation(requestMethod, rawResponse, requestPath), + }; + } + else if (getLocation(rawResponse) !== undefined) { + return { + mode: "Location", + }; + } + else if (["PUT", "PATCH"].includes(requestMethod)) { + return { + mode: "Body", + }; + } + return {}; +} +class SimpleRestError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "RestError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, SimpleRestError.prototype); + } +} +function isUnexpectedInitialResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![203, 204, 202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code); + } + return false; +} +function isUnexpectedPollingResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); + } + return false; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const successStates = ["succeeded"]; +const failureStates = ["failed", "canceled", "cancelled"]; + +// Copyright (c) Microsoft Corporation. +function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return typeof state === "string" ? state.toLowerCase() : "succeeded"; +} +function isBodyPollingDone(rawResponse) { + const state = getProvisioningState(rawResponse); + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Creates a polling strategy based on BodyPolling which uses the provisioning state + * from the result to determine the current operation state + */ +function processBodyPollingOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) }); +} + +// Copyright (c) Microsoft Corporation. +/** + * The `@azure/logger` configuration for this package. + * @internal + */ +const logger = logger$1.createClientLogger("core-lro"); + +// Copyright (c) Microsoft Corporation. +function isPollingDone(rawResponse) { + var _a; + if (isUnexpectedPollingResponse(rawResponse) || rawResponse.statusCode === 202) { + return false; + } + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = typeof status === "string" ? status.toLowerCase() : "succeeded"; + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Sends a request to the URI of the provisioned resource if needed. + */ +async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) { + switch (lroResourceLocationConfig) { + case "original-uri": + return lro.sendPollRequest(lro.requestPath); + case "azure-async-operation": + return undefined; + case "location": + default: + return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath); + } +} +function processLocationPollingOperationResult(lro, resourceLocation, lroResourceLocationConfig) { + return (response) => { + if (isPollingDone(response.rawResponse)) { + if (resourceLocation === undefined) { + return Object.assign(Object.assign({}, response), { done: true }); + } + else { + return Object.assign(Object.assign({}, response), { done: false, next: async () => { + const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig); + return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true }); + } }); + } + } + return Object.assign(Object.assign({}, response), { done: false }); + }; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +function processPassthroughOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: true }); +} + +// Copyright (c) Microsoft Corporation. +/** + * creates a stepping function that maps an LRO state to another. + */ +function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) { + switch (config.mode) { + case "Location": { + return processLocationPollingOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig); + } + case "Body": { + return processBodyPollingOperationResult; + } + default: { + return processPassthroughOperationResult; + } + } +} +/** + * Creates a polling operation. + */ +function createPoll(lroPrimitives) { + return async (path, pollerConfig, getLroStatusFromResponse) => { + const response = await lroPrimitives.sendPollRequest(path); + const retryAfter = response.rawResponse.headers["retry-after"]; + if (retryAfter !== undefined) { + // Retry-After header value is either in HTTP date format, or in seconds + const retryAfterInSeconds = parseInt(retryAfter); + pollerConfig.intervalInMs = isNaN(retryAfterInSeconds) + ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) + : retryAfterInSeconds * 1000; + } + return getLroStatusFromResponse(response); + }; +} +function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { + const timeNow = Math.floor(new Date().getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return defaultIntervalInMs; +} +/** + * Creates a callback to be used to initialize the polling operation state. + * @param state - of the polling operation + * @param operationSpec - of the LRO + * @param callback - callback to be called when the operation is done + * @returns callback that initializes the state of the polling operation + */ +function createInitializeState(state, requestPath, requestMethod) { + return (response) => { + if (isUnexpectedInitialResponse(response.rawResponse)) + ; + state.initialRawResponse = response.rawResponse; + state.isStarted = true; + state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath); + state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse); + /** short circuit polling if body polling is done in the initial request */ + if (state.config.mode === undefined || + (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) { + state.result = response.flatResponse; + state.isCompleted = true; + } + logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`); + return Boolean(state.isCompleted); + }; +} + +// Copyright (c) Microsoft Corporation. +class GenericPollOperation { + constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + /** + * General update function for LROPoller, the general process is as follows + * 1. Check initial operation result to determine the strategy to use + * - Strategies: Location, Azure-AsyncOperation, Original Uri + * 2. Check if the operation result has a terminal state + * - Terminal state will be determined by each strategy + * 2.1 If it is terminal state Check if a final GET request is required, if so + * send final GET request and return result from operation. If no final GET + * is required, just return the result from operation. + * - Determining what to call for final request is responsibility of each strategy + * 2.2 If it is not terminal state, call the polling operation and go to step 1 + * - Determining what to call for polling is responsibility of each strategy + * - Strategies will always use the latest URI for polling if provided otherwise + * the last known one + */ + async update(options) { + var _a, _b, _c; + const state = this.state; + let lastResponse = undefined; + if (!state.isStarted) { + const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod); + lastResponse = await this.lro.sendInitialRequest(); + initializeState(lastResponse); + } + if (!state.isCompleted) { + if (!this.poll || !this.getLroStatusFromResponse) { + if (!state.config) { + throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed."); + } + const isDone = this.isDone; + this.getLroStatusFromResponse = isDone + ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) + : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig); + this.poll = createPoll(this.lro); + } + if (!state.pollingURL) { + throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed."); + } + const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse); + logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`); + if (currentState.done) { + state.result = this.processResult + ? this.processResult(currentState.flatResponse, state) + : currentState.flatResponse; + state.isCompleted = true; + } + else { + this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; + state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL); + } + lastResponse = currentState; + } + logger.verbose(`LRO: current state: ${JSON.stringify(state)}`); + if (lastResponse) { + (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); + } + else { + logger.error(`LRO: no response was received`); + } + (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); + return this; + } + async cancel() { + this.state.isCancelled = true; + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state, + }); + } +} + +// Copyright (c) Microsoft Corporation. +function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; + } + catch (e) { + throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); + } +} /** * The LRO Engine, a class that performs polling. */ class LroEngine extends Poller { constructor(lro, options) { - const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {}; + const { intervalInMs = 2000, resumeFrom } = options || {}; const state = resumeFrom ? deserializeState(resumeFrom) : {}; - const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone); + const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone); super(operation); - this.resolveOnUnsuccessful = resolveOnUnsuccessful; this.config = { intervalInMs: intervalInMs }; operation.setPollerConfig(this.config); } @@ -18245,7 +18228,6 @@ exports.LroEngine = LroEngine; exports.Poller = Poller; exports.PollerCancelledError = PollerCancelledError; exports.PollerStoppedError = PollerStoppedError; -exports.createHttpPoller = createHttpPoller; //# sourceMappingURL=index.js.map @@ -18259,6 +18241,7 @@ exports.createHttpPoller = createHttpPoller; Object.defineProperty(exports, "__esModule", ({ value: true })); +__nccwpck_require__(2356); var tslib = __nccwpck_require__(6429); // Copyright (c) Microsoft Corporation. @@ -18280,78 +18263,47 @@ function getPagedAsyncIterator(pagedResult) { return this; }, byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => { - const { continuationToken, maxPageSize } = settings !== null && settings !== void 0 ? settings : {}; - return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, - maxPageSize, - }); + return getPageAsyncIterator(pagedResult, settings === null || settings === void 0 ? void 0 : settings.maxPageSize); }), }; } -function getItemAsyncIterator(pagedResult) { +function getItemAsyncIterator(pagedResult, maxPageSize) { return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() { - var e_1, _a, e_2, _b; - const pages = getPageAsyncIterator(pagedResult); + var e_1, _a; + const pages = getPageAsyncIterator(pagedResult, maxPageSize); const firstVal = yield tslib.__await(pages.next()); // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(firstVal.value)))); - try { - for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { - const page = pages_1_1.value; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(page)))); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); - } - finally { if (e_1) throw e_1.error; } - } - } - else { - yield yield tslib.__await(firstVal.value); - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); - } + yield yield tslib.__await(firstVal.value); + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); } else { yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value))); try { - for (var pages_2 = tslib.__asyncValues(pages), pages_2_1; pages_2_1 = yield tslib.__await(pages_2.next()), !pages_2_1.done;) { - const page = pages_2_1.value; + for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { + const page = pages_1_1.value; // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, // it must be the case that `TPage = TElement[]` yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page))); } } - catch (e_2_1) { e_2 = { error: e_2_1 }; } + catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (pages_2_1 && !pages_2_1.done && (_b = pages_2.return)) yield tslib.__await(_b.call(pages_2)); + if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); } - finally { if (e_2) throw e_2.error; } + finally { if (e_1) throw e_1.error; } } } }); } -function getPageAsyncIterator(pagedResult, options = {}) { +function getPageAsyncIterator(pagedResult, maxPageSize) { return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() { - const { pageLink, maxPageSize } = options; - let response = yield tslib.__await(pagedResult.getPage(pageLink !== null && pageLink !== void 0 ? pageLink : pagedResult.firstPageLink, maxPageSize)); - if (!response) { - return yield tslib.__await(void 0); - } + let response = yield tslib.__await(pagedResult.getPage(pagedResult.firstPageLink, maxPageSize)); yield yield tslib.__await(response.page); while (response.nextPageLink) { response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); - if (!response) { - return yield tslib.__await(void 0); - } yield yield tslib.__await(response.page); } }); @@ -18366,7 +18318,7 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator; /***/ 6429: /***/ ((module) => { -/****************************************************************************** +/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -18386,10 +18338,6 @@ var __assign; var __rest; var __decorate; var __param; -var __esDecorate; -var __runInitializers; -var __propKey; -var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -18408,7 +18356,6 @@ var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; -var __classPrivateFieldIn; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; @@ -18477,51 +18424,6 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; - __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.push(_); - } - else if (_ = accept(result)) { - if (kind === "field") initializers.push(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - - __runInitializers = function (thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; - }; - - __propKey = function (x) { - return typeof x === "symbol" ? x : "".concat(x); - }; - - __setFunctionName = function (f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); - }; - __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; @@ -18542,7 +18444,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { + while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -18570,11 +18472,7 @@ var __createBinding; __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -18654,7 +18552,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -18701,20 +18599,11 @@ var __createBinding; return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; - __classPrivateFieldIn = function (state, receiver) { - if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); - exporter("__esDecorate", __esDecorate); - exporter("__runInitializers", __runInitializers); - exporter("__propKey", __propKey); - exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -18734,7 +18623,6 @@ var __createBinding; exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); - exporter("__classPrivateFieldIn", __classPrivateFieldIn); }); @@ -19217,16 +19105,14 @@ exports.randomUUID = randomUUID; Object.defineProperty(exports, "__esModule", ({ value: true })); -var os = __nccwpck_require__(2037); -var util = __nccwpck_require__(3837); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var util__default = /*#__PURE__*/_interopDefaultLegacy(util); +var util = _interopDefault(__nccwpck_require__(3837)); +var os = __nccwpck_require__(2037); // Copyright (c) Microsoft Corporation. function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); + process.stderr.write(`${util.format(message, ...args)}${os.EOL}`); } // Copyright (c) Microsoft Corporation. @@ -19244,7 +19130,7 @@ const debugObj = Object.assign((namespace) => { enable, enabled, disable, - log, + log }); function enable(namespaces) { enabledString = namespaces; @@ -19291,7 +19177,7 @@ function createDebugger(namespace) { destroy, log: debugObj.log, namespace, - extend, + extend }); function debug(...args) { if (!newDebugger.enabled) { @@ -19318,7 +19204,6 @@ function extend(namespace) { newDebugger.log = this.log; return newDebugger; } -var debug = debugObj; // Copyright (c) Microsoft Corporation. const registeredLoggers = new Set(); @@ -19329,9 +19214,9 @@ let azureLogLevel; * By default, logs are sent to stderr. * Override the `log` method to redirect logs to another location. */ -const AzureLogger = debug("azure"); +const AzureLogger = debugObj("azure"); AzureLogger.log = (...args) => { - debug.log(...args); + debugObj.log(...args); }; const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; if (logLevelFromEnv) { @@ -19344,7 +19229,7 @@ if (logLevelFromEnv) { } } /** - * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. + * Immediately enables logging at the specified log level. * @param level - The log level to enable for logging. * Options from most verbose to least verbose are: * - verbose @@ -19363,7 +19248,7 @@ function setLogLevel(level) { enabledNamespaces.push(logger.namespace); } } - debug.enable(enabledNamespaces.join(",")); + debugObj.enable(enabledNamespaces.join(",")); } /** * Retrieves the currently specified log level. @@ -19375,7 +19260,7 @@ const levelMap = { verbose: 400, info: 300, warning: 200, - error: 100, + error: 100 }; /** * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. @@ -19389,7 +19274,7 @@ function createClientLogger(namespace) { error: createLogger(clientRootLogger, "error"), warning: createLogger(clientRootLogger, "warning"), info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose"), + verbose: createLogger(clientRootLogger, "verbose") }; } function patchLogMethod(parent, child) { @@ -19399,18 +19284,23 @@ function patchLogMethod(parent, child) { } function createLogger(parent, level) { const logger = Object.assign(parent.extend(level), { - level, + level }); patchLogMethod(parent, logger); if (shouldEnable(logger)) { - const enabledNamespaces = debug.disable(); - debug.enable(enabledNamespaces + "," + logger.namespace); + const enabledNamespaces = debugObj.disable(); + debugObj.enable(enabledNamespaces + "," + logger.namespace); } registeredLoggers.add(logger); return logger; } function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + if (azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]) { + return true; + } + else { + return false; + } } function isAzureLogLevel(logLevel) { return AZURE_LOG_LEVELS.includes(logLevel); @@ -44551,7 +44441,7 @@ exports.newPipeline = newPipeline; /***/ 679: /***/ ((module) => { -/****************************************************************************** +/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -44571,10 +44461,6 @@ var __assign; var __rest; var __decorate; var __param; -var __esDecorate; -var __runInitializers; -var __propKey; -var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -44593,7 +44479,6 @@ var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; -var __classPrivateFieldIn; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; @@ -44662,51 +44547,6 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; - __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.push(_); - } - else if (_ = accept(result)) { - if (kind === "field") initializers.push(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - - __runInitializers = function (thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; - }; - - __propKey = function (x) { - return typeof x === "symbol" ? x : "".concat(x); - }; - - __setFunctionName = function (f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); - }; - __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; @@ -44727,7 +44567,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { + while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -44755,11 +44595,7 @@ var __createBinding; __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -44839,7 +44675,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -44886,20 +44722,11 @@ var __createBinding; return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; - __classPrivateFieldIn = function (state, receiver) { - if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); - exporter("__esDecorate", __esDecorate); - exporter("__runInitializers", __runInitializers); - exporter("__propKey", __propKey); - exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -44919,7 +44746,6 @@ var __createBinding; exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); - exporter("__classPrivateFieldIn", __classPrivateFieldIn); }); @@ -47148,7 +46974,7 @@ function validate(octokit, options) { /***/ }), /***/ 7171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -47167,40 +46993,46 @@ function validate(octokit, options) { * See the License for the specific language governing permissions and * limitations under the License. */ +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; -const NoopContextManager_1 = __nccwpck_require__(4118); -const global_utils_1 = __nccwpck_require__(5135); -const diag_1 = __nccwpck_require__(1877); -const API_NAME = 'context'; -const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); +var NoopContextManager_1 = __nccwpck_require__(4118); +var global_utils_1 = __nccwpck_require__(5135); +var diag_1 = __nccwpck_require__(1877); +var API_NAME = 'context'; +var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** * Singleton object which represents the entry point to the OpenTelemetry Context API */ -class ContextAPI { +var ContextAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } + function ContextAPI() { + } /** Get the singleton instance of the Context API */ - static getInstance() { + ContextAPI.getInstance = function () { if (!this._instance) { this._instance = new ContextAPI(); } return this._instance; - } + }; /** * Set the current context manager. * * @returns true if the context manager was successfully registered, else false */ - setGlobalContextManager(contextManager) { - return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); - } + ContextAPI.prototype.setGlobalContextManager = function (contextManager) { + return global_utils_1.registerGlobal(API_NAME, contextManager, diag_1.DiagAPI.instance()); + }; /** * Get the currently active context */ - active() { + ContextAPI.prototype.active = function () { return this._getContextManager().active(); - } + }; /** * Execute a function with an active context * @@ -47209,27 +47041,33 @@ class ContextAPI { * @param thisArg optional receiver to be used for calling fn * @param args optional arguments forwarded to fn */ - with(context, fn, thisArg, ...args) { - return this._getContextManager().with(context, fn, thisArg, ...args); - } + ContextAPI.prototype.with = function (context, fn, thisArg) { + var _a; + var args = []; + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], args)); + }; /** * Bind a context to a target function or event emitter * * @param context context to bind to the event emitter or function. Defaults to the currently active context * @param target function or event emitter to bind */ - bind(context, target) { + ContextAPI.prototype.bind = function (context, target) { return this._getContextManager().bind(context, target); - } - _getContextManager() { - return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; - } + }; + ContextAPI.prototype._getContextManager = function () { + return global_utils_1.getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER; + }; /** Disable and remove the global context manager */ - disable() { + ContextAPI.prototype.disable = function () { this._getContextManager().disable(); - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } -} + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); + }; + return ContextAPI; +}()); exports.ContextAPI = ContextAPI; //# sourceMappingURL=context.js.map @@ -47257,63 +47095,62 @@ exports.ContextAPI = ContextAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; -const ComponentLogger_1 = __nccwpck_require__(7978); -const logLevelLogger_1 = __nccwpck_require__(9639); -const types_1 = __nccwpck_require__(8077); -const global_utils_1 = __nccwpck_require__(5135); -const API_NAME = 'diag'; +var ComponentLogger_1 = __nccwpck_require__(7978); +var logLevelLogger_1 = __nccwpck_require__(9639); +var types_1 = __nccwpck_require__(8077); +var global_utils_1 = __nccwpck_require__(5135); +var API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal * diagnostic API */ -class DiagAPI { +var DiagAPI = /** @class */ (function () { /** * Private internal constructor * @private */ - constructor() { + function DiagAPI() { function _logProxy(funcName) { - return function (...args) { - const logger = (0, global_utils_1.getGlobal)('diag'); + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var logger = global_utils_1.getGlobal('diag'); // shortcut if logger not set if (!logger) return; - return logger[funcName](...args); + return logger[funcName].apply(logger, args); }; } // Using self local variable for minification purposes as 'this' cannot be minified - const self = this; + var self = this; // DiagAPI specific functions - const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { - var _a, _b, _c; + self.setLogger = function (logger, logLevel) { + var _a, _b; + if (logLevel === void 0) { logLevel = types_1.DiagLogLevel.INFO; } if (logger === self) { // There isn't much we can do here. // Logging to the console might break the user application. // Try to log to self. If a logger was previously registered it will receive the log. - const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); return false; } - if (typeof optionsOrLogLevel === 'number') { - optionsOrLogLevel = { - logLevel: optionsOrLogLevel, - }; - } - const oldLogger = (0, global_utils_1.getGlobal)('diag'); - const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); + var oldLogger = global_utils_1.getGlobal('diag'); + var newLogger = logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger); // There already is an logger registered. We'll let it know before overwriting it. - if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { - const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; - oldLogger.warn(`Current logger will be overwritten from ${stack}`); - newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + if (oldLogger) { + var stack = (_b = new Error().stack) !== null && _b !== void 0 ? _b : ''; + oldLogger.warn("Current logger will be overwritten from " + stack); + newLogger.warn("Current logger will overwrite one already registered from " + stack); } - return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); + return global_utils_1.registerGlobal('diag', newLogger, self, true); }; - self.setLogger = setLogger; - self.disable = () => { - (0, global_utils_1.unregisterGlobal)(API_NAME, self); + self.disable = function () { + global_utils_1.unregisterGlobal(API_NAME, self); }; - self.createComponentLogger = (options) => { + self.createComponentLogger = function (options) { return new ComponentLogger_1.DiagComponentLogger(options); }; self.verbose = _logProxy('verbose'); @@ -47323,86 +47160,19 @@ class DiagAPI { self.error = _logProxy('error'); } /** Get the singleton instance of the DiagAPI API */ - static instance() { + DiagAPI.instance = function () { if (!this._instance) { this._instance = new DiagAPI(); } return this._instance; - } -} + }; + return DiagAPI; +}()); exports.DiagAPI = DiagAPI; //# sourceMappingURL=diag.js.map /***/ }), -/***/ 7696: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MetricsAPI = void 0; -const NoopMeterProvider_1 = __nccwpck_require__(2647); -const global_utils_1 = __nccwpck_require__(5135); -const diag_1 = __nccwpck_require__(1877); -const API_NAME = 'metrics'; -/** - * Singleton object which represents the entry point to the OpenTelemetry Metrics API - */ -class MetricsAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } - /** Get the singleton instance of the Metrics API */ - static getInstance() { - if (!this._instance) { - this._instance = new MetricsAPI(); - } - return this._instance; - } - /** - * Set the current global meter provider. - * Returns true if the meter provider was successfully registered, else false. - */ - setGlobalMeterProvider(provider) { - return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); - } - /** - * Returns the global meter provider. - */ - getMeterProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; - } - /** - * Returns a meter from the global meter provider. - */ - getMeter(name, version, options) { - return this.getMeterProvider().getMeter(name, version, options); - } - /** Remove the global meter provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } -} -exports.MetricsAPI = MetricsAPI; -//# sourceMappingURL=metrics.js.map - -/***/ }), - /***/ 9909: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -47425,41 +47195,40 @@ exports.MetricsAPI = MetricsAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; -const global_utils_1 = __nccwpck_require__(5135); -const NoopTextMapPropagator_1 = __nccwpck_require__(2368); -const TextMapPropagator_1 = __nccwpck_require__(865); -const context_helpers_1 = __nccwpck_require__(7682); -const utils_1 = __nccwpck_require__(8136); -const diag_1 = __nccwpck_require__(1877); -const API_NAME = 'propagation'; -const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); +var global_utils_1 = __nccwpck_require__(5135); +var NoopTextMapPropagator_1 = __nccwpck_require__(2368); +var TextMapPropagator_1 = __nccwpck_require__(865); +var context_helpers_1 = __nccwpck_require__(7682); +var utils_1 = __nccwpck_require__(8136); +var diag_1 = __nccwpck_require__(1877); +var API_NAME = 'propagation'; +var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** * Singleton object which represents the entry point to the OpenTelemetry Propagation API */ -class PropagationAPI { +var PropagationAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { + function PropagationAPI() { this.createBaggage = utils_1.createBaggage; this.getBaggage = context_helpers_1.getBaggage; - this.getActiveBaggage = context_helpers_1.getActiveBaggage; this.setBaggage = context_helpers_1.setBaggage; this.deleteBaggage = context_helpers_1.deleteBaggage; } /** Get the singleton instance of the Propagator API */ - static getInstance() { + PropagationAPI.getInstance = function () { if (!this._instance) { this._instance = new PropagationAPI(); } return this._instance; - } + }; /** * Set the current propagator. * * @returns true if the propagator was successfully registered, else false */ - setGlobalPropagator(propagator) { - return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); - } + PropagationAPI.prototype.setGlobalPropagator = function (propagator) { + return global_utils_1.registerGlobal(API_NAME, propagator, diag_1.DiagAPI.instance()); + }; /** * Inject context into a carrier to be propagated inter-process * @@ -47467,9 +47236,10 @@ class PropagationAPI { * @param carrier carrier to inject context into * @param setter Function used to set values on the carrier */ - inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { + PropagationAPI.prototype.inject = function (context, carrier, setter) { + if (setter === void 0) { setter = TextMapPropagator_1.defaultTextMapSetter; } return this._getGlobalPropagator().inject(context, carrier, setter); - } + }; /** * Extract context from a carrier * @@ -47477,23 +47247,25 @@ class PropagationAPI { * @param carrier Carrier to extract context from * @param getter Function used to extract keys from a carrier */ - extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { + PropagationAPI.prototype.extract = function (context, carrier, getter) { + if (getter === void 0) { getter = TextMapPropagator_1.defaultTextMapGetter; } return this._getGlobalPropagator().extract(context, carrier, getter); - } + }; /** * Return a list of all fields which may be used by the propagator. */ - fields() { + PropagationAPI.prototype.fields = function () { return this._getGlobalPropagator().fields(); - } + }; /** Remove the global propagator */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } - _getGlobalPropagator() { - return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; - } -} + PropagationAPI.prototype.disable = function () { + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); + }; + PropagationAPI.prototype._getGlobalPropagator = function () { + return global_utils_1.getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + }; + return PropagationAPI; +}()); exports.PropagationAPI = PropagationAPI; //# sourceMappingURL=propagation.js.map @@ -47521,65 +47293,65 @@ exports.PropagationAPI = PropagationAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; -const global_utils_1 = __nccwpck_require__(5135); -const ProxyTracerProvider_1 = __nccwpck_require__(2285); -const spancontext_utils_1 = __nccwpck_require__(9745); -const context_utils_1 = __nccwpck_require__(3326); -const diag_1 = __nccwpck_require__(1877); -const API_NAME = 'trace'; +var global_utils_1 = __nccwpck_require__(5135); +var ProxyTracerProvider_1 = __nccwpck_require__(2285); +var spancontext_utils_1 = __nccwpck_require__(9745); +var context_utils_1 = __nccwpck_require__(3326); +var diag_1 = __nccwpck_require__(1877); +var API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API */ -class TraceAPI { +var TraceAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { + function TraceAPI() { this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; this.deleteSpan = context_utils_1.deleteSpan; this.getSpan = context_utils_1.getSpan; - this.getActiveSpan = context_utils_1.getActiveSpan; this.getSpanContext = context_utils_1.getSpanContext; this.setSpan = context_utils_1.setSpan; this.setSpanContext = context_utils_1.setSpanContext; } /** Get the singleton instance of the Trace API */ - static getInstance() { + TraceAPI.getInstance = function () { if (!this._instance) { this._instance = new TraceAPI(); } return this._instance; - } + }; /** * Set the current global tracer. * * @returns true if the tracer provider was successfully registered, else false */ - setGlobalTracerProvider(provider) { - const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + TraceAPI.prototype.setGlobalTracerProvider = function (provider) { + var success = global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); if (success) { this._proxyTracerProvider.setDelegate(provider); } return success; - } + }; /** * Returns the global tracer provider. */ - getTracerProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; - } + TraceAPI.prototype.getTracerProvider = function () { + return global_utils_1.getGlobal(API_NAME) || this._proxyTracerProvider; + }; /** * Returns a tracer from the global tracer provider. */ - getTracer(name, version) { + TraceAPI.prototype.getTracer = function (name, version) { return this.getTracerProvider().getTracer(name, version); - } + }; /** Remove the global tracer provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + TraceAPI.prototype.disable = function () { + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - } -} + }; + return TraceAPI; +}()); exports.TraceAPI = TraceAPI; //# sourceMappingURL=trace.js.map @@ -47606,13 +47378,12 @@ exports.TraceAPI = TraceAPI; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; -const context_1 = __nccwpck_require__(7171); -const context_2 = __nccwpck_require__(8242); +exports.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0; +var context_1 = __nccwpck_require__(8242); /** * Baggage key */ -const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); +var BAGGAGE_KEY = context_1.createContextKey('OpenTelemetry Baggage Key'); /** * Retrieve the current baggage from the given context * @@ -47623,15 +47394,6 @@ function getBaggage(context) { return context.getValue(BAGGAGE_KEY) || undefined; } exports.getBaggage = getBaggage; -/** - * Retrieve the current baggage from the active/current context - * - * @returns {Baggage} Extracted baggage from the context - */ -function getActiveBaggage() { - return getBaggage(context_1.ContextAPI.getInstance().active()); -} -exports.getActiveBaggage = getActiveBaggage; /** * Store a baggage in the given context * @@ -47677,41 +47439,50 @@ exports.deleteBaggage = deleteBaggage; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaggageImpl = void 0; -class BaggageImpl { - constructor(entries) { +var BaggageImpl = /** @class */ (function () { + function BaggageImpl(entries) { this._entries = entries ? new Map(entries) : new Map(); } - getEntry(key) { - const entry = this._entries.get(key); + BaggageImpl.prototype.getEntry = function (key) { + var entry = this._entries.get(key); if (!entry) { return undefined; } return Object.assign({}, entry); - } - getAllEntries() { - return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); - } - setEntry(key, entry) { - const newBaggage = new BaggageImpl(this._entries); + }; + BaggageImpl.prototype.getAllEntries = function () { + return Array.from(this._entries.entries()).map(function (_a) { + var k = _a[0], v = _a[1]; + return [k, v]; + }); + }; + BaggageImpl.prototype.setEntry = function (key, entry) { + var newBaggage = new BaggageImpl(this._entries); newBaggage._entries.set(key, entry); return newBaggage; - } - removeEntry(key) { - const newBaggage = new BaggageImpl(this._entries); + }; + BaggageImpl.prototype.removeEntry = function (key) { + var newBaggage = new BaggageImpl(this._entries); newBaggage._entries.delete(key); return newBaggage; - } - removeEntries(...keys) { - const newBaggage = new BaggageImpl(this._entries); - for (const key of keys) { + }; + BaggageImpl.prototype.removeEntries = function () { + var keys = []; + for (var _i = 0; _i < arguments.length; _i++) { + keys[_i] = arguments[_i]; + } + var newBaggage = new BaggageImpl(this._entries); + for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { + var key = keys_1[_a]; newBaggage._entries.delete(key); } return newBaggage; - } - clear() { + }; + BaggageImpl.prototype.clear = function () { return new BaggageImpl(); - } -} + }; + return BaggageImpl; +}()); exports.BaggageImpl = BaggageImpl; //# sourceMappingURL=baggage-impl.js.map @@ -47747,6 +47518,31 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); /***/ }), +/***/ 1508: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=types.js.map + +/***/ }), + /***/ 8136: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -47769,16 +47565,17 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -const diag_1 = __nccwpck_require__(1877); -const baggage_impl_1 = __nccwpck_require__(4811); -const symbol_1 = __nccwpck_require__(3542); -const diag = diag_1.DiagAPI.instance(); +var diag_1 = __nccwpck_require__(1877); +var baggage_impl_1 = __nccwpck_require__(4811); +var symbol_1 = __nccwpck_require__(3542); +var diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries * * @param entries An array of baggage entries the new baggage should contain */ -function createBaggage(entries = {}) { +function createBaggage(entries) { + if (entries === void 0) { entries = {}; } return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); } exports.createBaggage = createBaggage; @@ -47790,12 +47587,12 @@ exports.createBaggage = createBaggage; */ function baggageEntryMetadataFromString(str) { if (typeof str !== 'string') { - diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + diag.error("Cannot create baggage metadata from unknown type: " + typeof str); str = ''; } return { __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString() { + toString: function () { return str; }, }; @@ -47805,8 +47602,8 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; /***/ }), -/***/ 7393: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4447: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -47826,18 +47623,22 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.context = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const context_1 = __nccwpck_require__(7171); -/** Entrypoint for context API */ -exports.context = context_1.ContextAPI.getInstance(); -//# sourceMappingURL=context-api.js.map +//# sourceMappingURL=Exception.js.map + +/***/ }), + +/***/ 656: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=Time.js.map /***/ }), /***/ 4118: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -47856,26 +47657,38 @@ exports.context = context_1.ContextAPI.getInstance(); * See the License for the specific language governing permissions and * limitations under the License. */ +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; -const context_1 = __nccwpck_require__(8242); -class NoopContextManager { - active() { - return context_1.ROOT_CONTEXT; - } - with(_context, fn, thisArg, ...args) { - return fn.call(thisArg, ...args); +var context_1 = __nccwpck_require__(8242); +var NoopContextManager = /** @class */ (function () { + function NoopContextManager() { } - bind(_context, target) { + NoopContextManager.prototype.active = function () { + return context_1.ROOT_CONTEXT; + }; + NoopContextManager.prototype.with = function (_context, fn, thisArg) { + var args = []; + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + return fn.call.apply(fn, __spreadArray([thisArg], args)); + }; + NoopContextManager.prototype.bind = function (_context, target) { return target; - } - enable() { + }; + NoopContextManager.prototype.enable = function () { return this; - } - disable() { + }; + NoopContextManager.prototype.disable = function () { return this; - } -} + }; + return NoopContextManager; +}()); exports.NoopContextManager = NoopContextManager; //# sourceMappingURL=NoopContextManager.js.map @@ -47914,37 +47727,38 @@ function createContextKey(description) { return Symbol.for(description); } exports.createContextKey = createContextKey; -class BaseContext { +var BaseContext = /** @class */ (function () { /** * Construct a new context which inherits values from an optional parent context. * * @param parentContext a context from which to inherit values */ - constructor(parentContext) { + function BaseContext(parentContext) { // for minification - const self = this; + var self = this; self._currentContext = parentContext ? new Map(parentContext) : new Map(); - self.getValue = (key) => self._currentContext.get(key); - self.setValue = (key, value) => { - const context = new BaseContext(self._currentContext); + self.getValue = function (key) { return self._currentContext.get(key); }; + self.setValue = function (key, value) { + var context = new BaseContext(self._currentContext); context._currentContext.set(key, value); return context; }; - self.deleteValue = (key) => { - const context = new BaseContext(self._currentContext); + self.deleteValue = function (key) { + var context = new BaseContext(self._currentContext); context._currentContext.delete(key); return context; }; } -} + return BaseContext; +}()); /** The root context is used as the default parent context when there is no active context */ exports.ROOT_CONTEXT = new BaseContext(); //# sourceMappingURL=context.js.map /***/ }), -/***/ 9721: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 6504: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -47964,18 +47778,7 @@ exports.ROOT_CONTEXT = new BaseContext(); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.diag = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const diag_1 = __nccwpck_require__(1877); -/** - * Entrypoint for Diag API. - * Defines Diagnostic handler used for internal diagnostic logging operations. - * The default provides a Noop DiagLogger implementation which may be changed via the - * diag.setLogger(logger: DiagLogger) function. - */ -exports.diag = diag_1.DiagAPI.instance(); -//# sourceMappingURL=diag-api.js.map +//# sourceMappingURL=types.js.map /***/ }), @@ -48001,7 +47804,7 @@ exports.diag = diag_1.DiagAPI.instance(); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; -const global_utils_1 = __nccwpck_require__(5135); +var global_utils_1 = __nccwpck_require__(5135); /** * Component Logger which is meant to be used as part of any component which * will add automatically additional namespace in front of the log message. @@ -48011,35 +47814,56 @@ const global_utils_1 = __nccwpck_require__(5135); * cLogger.debug('test'); * // @opentelemetry/instrumentation-http test */ -class DiagComponentLogger { - constructor(props) { +var DiagComponentLogger = /** @class */ (function () { + function DiagComponentLogger(props) { this._namespace = props.namespace || 'DiagComponentLogger'; } - debug(...args) { + DiagComponentLogger.prototype.debug = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('debug', this._namespace, args); - } - error(...args) { + }; + DiagComponentLogger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('error', this._namespace, args); - } - info(...args) { + }; + DiagComponentLogger.prototype.info = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('info', this._namespace, args); - } - warn(...args) { + }; + DiagComponentLogger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('warn', this._namespace, args); - } - verbose(...args) { + }; + DiagComponentLogger.prototype.verbose = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } return logProxy('verbose', this._namespace, args); - } -} + }; + return DiagComponentLogger; +}()); exports.DiagComponentLogger = DiagComponentLogger; function logProxy(funcName, namespace, args) { - const logger = (0, global_utils_1.getGlobal)('diag'); + var logger = global_utils_1.getGlobal('diag'); // shortcut if logger not set if (!logger) { return; } args.unshift(namespace); - return logger[funcName](...args); + return logger[funcName].apply(logger, args); } //# sourceMappingURL=ComponentLogger.js.map @@ -48067,7 +47891,7 @@ function logProxy(funcName, namespace, args) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagConsoleLogger = void 0; -const consoleMap = [ +var consoleMap = [ { n: 'error', c: 'error' }, { n: 'warn', c: 'warn' }, { n: 'info', c: 'info' }, @@ -48079,14 +47903,18 @@ const consoleMap = [ * If you want to limit the amount of logging to a specific level or lower use the * {@link createLogLevelDiagLogger} */ -class DiagConsoleLogger { - constructor() { +var DiagConsoleLogger = /** @class */ (function () { + function DiagConsoleLogger() { function _consoleFunc(funcName) { - return function (...args) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } if (console) { // Some environments only expose the console when the F12 developer console is open // eslint-disable-next-line no-console - let theFunc = console[funcName]; + var theFunc = console[funcName]; if (typeof theFunc !== 'function') { // Not all environments support all functions // eslint-disable-next-line no-console @@ -48099,16 +47927,54 @@ class DiagConsoleLogger { } }; } - for (let i = 0; i < consoleMap.length; i++) { + for (var i = 0; i < consoleMap.length; i++) { this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); } } -} + return DiagConsoleLogger; +}()); exports.DiagConsoleLogger = DiagConsoleLogger; //# sourceMappingURL=consoleLogger.js.map /***/ }), +/***/ 1634: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(3041), exports); +__exportStar(__nccwpck_require__(8077), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + /***/ 9639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -48131,7 +47997,7 @@ exports.DiagConsoleLogger = DiagConsoleLogger; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; -const types_1 = __nccwpck_require__(8077); +var types_1 = __nccwpck_require__(8077); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; @@ -48142,7 +48008,7 @@ function createLogLevelDiagLogger(maxLevel, logger) { // In case the logger is null or undefined logger = logger || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + var theFunc = logger[funcName]; if (typeof theFunc === 'function' && maxLevel >= theLevel) { return theFunc.bind(logger); } @@ -48213,7 +48079,7 @@ var DiagLogLevel; /***/ }), /***/ 5163: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -48232,42 +48098,40 @@ var DiagLogLevel; * See the License for the specific language governing permissions and * limitations under the License. */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; +exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.baggageEntryMetadataFromString = void 0; +__exportStar(__nccwpck_require__(1508), exports); var utils_1 = __nccwpck_require__(8136); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); -// Context APIs -var context_1 = __nccwpck_require__(8242); -Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); -Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); -// Diag APIs -var consoleLogger_1 = __nccwpck_require__(3041); -Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); -var types_1 = __nccwpck_require__(8077); -Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); -// Metrics APIs -var NoopMeter_1 = __nccwpck_require__(4837); -Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); -var Metric_1 = __nccwpck_require__(9999); -Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); -// Propagation APIs -var TextMapPropagator_1 = __nccwpck_require__(865); -Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); -Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); -var ProxyTracer_1 = __nccwpck_require__(3503); -Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); -var ProxyTracerProvider_1 = __nccwpck_require__(2285); -Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); -var SamplingResult_1 = __nccwpck_require__(3209); -Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); -var span_kind_1 = __nccwpck_require__(1424); -Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); -var status_1 = __nccwpck_require__(8845); -Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); -var trace_flags_1 = __nccwpck_require__(6905); -Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); -var utils_2 = __nccwpck_require__(2615); -Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); +__exportStar(__nccwpck_require__(4447), exports); +__exportStar(__nccwpck_require__(656), exports); +__exportStar(__nccwpck_require__(1634), exports); +__exportStar(__nccwpck_require__(865), exports); +__exportStar(__nccwpck_require__(7492), exports); +__exportStar(__nccwpck_require__(4023), exports); +__exportStar(__nccwpck_require__(3503), exports); +__exportStar(__nccwpck_require__(2285), exports); +__exportStar(__nccwpck_require__(9671), exports); +__exportStar(__nccwpck_require__(3209), exports); +__exportStar(__nccwpck_require__(5769), exports); +__exportStar(__nccwpck_require__(1424), exports); +__exportStar(__nccwpck_require__(4416), exports); +__exportStar(__nccwpck_require__(955), exports); +__exportStar(__nccwpck_require__(8845), exports); +__exportStar(__nccwpck_require__(6905), exports); +__exportStar(__nccwpck_require__(8384), exports); +__exportStar(__nccwpck_require__(891), exports); +__exportStar(__nccwpck_require__(3168), exports); var spancontext_utils_1 = __nccwpck_require__(9745); Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); @@ -48276,25 +48140,30 @@ var invalid_span_constants_1 = __nccwpck_require__(1760); Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const context_api_1 = __nccwpck_require__(7393); -Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); -const diag_api_1 = __nccwpck_require__(9721); -Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); -const metrics_api_1 = __nccwpck_require__(2601); -Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); -const propagation_api_1 = __nccwpck_require__(7591); -Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); -const trace_api_1 = __nccwpck_require__(8989); -Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); -// Default export. +__exportStar(__nccwpck_require__(8242), exports); +__exportStar(__nccwpck_require__(6504), exports); +var context_1 = __nccwpck_require__(7171); +/** Entrypoint for context API */ +exports.context = context_1.ContextAPI.getInstance(); +var trace_1 = __nccwpck_require__(1539); +/** Entrypoint for trace API */ +exports.trace = trace_1.TraceAPI.getInstance(); +var propagation_1 = __nccwpck_require__(9909); +/** Entrypoint for propagation API */ +exports.propagation = propagation_1.PropagationAPI.getInstance(); +var diag_1 = __nccwpck_require__(1877); +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +exports.diag = diag_1.DiagAPI.instance(); exports["default"] = { - context: context_api_1.context, - diag: diag_api_1.diag, - metrics: metrics_api_1.metrics, - propagation: propagation_api_1.propagation, - trace: trace_api_1.trace, + trace: exports.trace, + context: exports.context, + propagation: exports.propagation, + diag: exports.diag, }; //# sourceMappingURL=index.js.map @@ -48322,46 +48191,47 @@ exports["default"] = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -const platform_1 = __nccwpck_require__(9957); -const version_1 = __nccwpck_require__(8996); -const semver_1 = __nccwpck_require__(1522); -const major = version_1.VERSION.split('.')[0]; -const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); -const _global = platform_1._globalThis; -function registerGlobal(type, instance, diag, allowOverride = false) { +var platform_1 = __nccwpck_require__(9957); +var version_1 = __nccwpck_require__(8996); +var semver_1 = __nccwpck_require__(1522); +var major = version_1.VERSION.split('.')[0]; +var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); +var _global = platform_1._globalThis; +function registerGlobal(type, instance, diag, allowOverride) { var _a; - const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + if (allowOverride === void 0) { allowOverride = false; } + var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: version_1.VERSION, }); if (!allowOverride && api[type]) { // already registered an API of this type - const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); diag.error(err.stack || err.message); return false; } if (api.version !== version_1.VERSION) { // All registered APIs must be of the same version exactly - const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); + var err = new Error('@opentelemetry/api: All API registration versions must match'); diag.error(err.stack || err.message); return false; } api[type] = instance; - diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); + diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + version_1.VERSION + "."); return true; } exports.registerGlobal = registerGlobal; function getGlobal(type) { var _a, _b; - const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; - if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { + var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !semver_1.isCompatible(globalVersion)) { return; } return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } exports.getGlobal = getGlobal; function unregisterGlobal(type, diag) { - diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); - const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + version_1.VERSION + "."); + var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; } @@ -48393,8 +48263,8 @@ exports.unregisterGlobal = unregisterGlobal; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; -const version_1 = __nccwpck_require__(8996); -const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +var version_1 = __nccwpck_require__(8996); +var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. * @@ -48412,14 +48282,14 @@ const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; * @param ownVersion version which should be checked against */ function _makeCompatibilityCheck(ownVersion) { - const acceptedVersions = new Set([ownVersion]); - const rejectedVersions = new Set(); - const myVersionMatch = ownVersion.match(re); + var acceptedVersions = new Set([ownVersion]); + var rejectedVersions = new Set(); + var myVersionMatch = ownVersion.match(re); if (!myVersionMatch) { // we cannot guarantee compatibility so we always return noop - return () => false; + return function () { return false; }; } - const ownVersionParsed = { + var ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], @@ -48446,13 +48316,13 @@ function _makeCompatibilityCheck(ownVersion) { if (rejectedVersions.has(globalVersion)) { return false; } - const globalVersionMatch = globalVersion.match(re); + var globalVersionMatch = globalVersion.match(re); if (!globalVersionMatch) { // cannot parse other version // we cannot guarantee compatibility so we always noop return _reject(globalVersion); } - const globalVersionParsed = { + var globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], @@ -48500,230 +48370,6 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); /***/ }), -/***/ 2601: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.metrics = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const metrics_1 = __nccwpck_require__(7696); -/** Entrypoint for metrics API */ -exports.metrics = metrics_1.MetricsAPI.getInstance(); -//# sourceMappingURL=metrics-api.js.map - -/***/ }), - -/***/ 9999: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ValueType = void 0; -/** The Type of value. It describes how the data is reported. */ -var ValueType; -(function (ValueType) { - ValueType[ValueType["INT"] = 0] = "INT"; - ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; -})(ValueType = exports.ValueType || (exports.ValueType = {})); -//# sourceMappingURL=Metric.js.map - -/***/ }), - -/***/ 4837: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; -/** - * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses - * constant NoopMetrics for all of its methods. - */ -class NoopMeter { - constructor() { } - /** - * @see {@link Meter.createHistogram} - */ - createHistogram(_name, _options) { - return exports.NOOP_HISTOGRAM_METRIC; - } - /** - * @see {@link Meter.createCounter} - */ - createCounter(_name, _options) { - return exports.NOOP_COUNTER_METRIC; - } - /** - * @see {@link Meter.createUpDownCounter} - */ - createUpDownCounter(_name, _options) { - return exports.NOOP_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableGauge} - */ - createObservableGauge(_name, _options) { - return exports.NOOP_OBSERVABLE_GAUGE_METRIC; - } - /** - * @see {@link Meter.createObservableCounter} - */ - createObservableCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableUpDownCounter} - */ - createObservableUpDownCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.addBatchObservableCallback} - */ - addBatchObservableCallback(_callback, _observables) { } - /** - * @see {@link Meter.removeBatchObservableCallback} - */ - removeBatchObservableCallback(_callback) { } -} -exports.NoopMeter = NoopMeter; -class NoopMetric { -} -exports.NoopMetric = NoopMetric; -class NoopCounterMetric extends NoopMetric { - add(_value, _attributes) { } -} -exports.NoopCounterMetric = NoopCounterMetric; -class NoopUpDownCounterMetric extends NoopMetric { - add(_value, _attributes) { } -} -exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; -class NoopHistogramMetric extends NoopMetric { - record(_value, _attributes) { } -} -exports.NoopHistogramMetric = NoopHistogramMetric; -class NoopObservableMetric { - addCallback(_callback) { } - removeCallback(_callback) { } -} -exports.NoopObservableMetric = NoopObservableMetric; -class NoopObservableCounterMetric extends NoopObservableMetric { -} -exports.NoopObservableCounterMetric = NoopObservableCounterMetric; -class NoopObservableGaugeMetric extends NoopObservableMetric { -} -exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; -class NoopObservableUpDownCounterMetric extends NoopObservableMetric { -} -exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; -exports.NOOP_METER = new NoopMeter(); -// Synchronous instruments -exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); -exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); -exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); -// Asynchronous instruments -exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); -exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); -exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); -/** - * Create a no-op Meter - */ -function createNoopMeter() { - return exports.NOOP_METER; -} -exports.createNoopMeter = createNoopMeter; -//# sourceMappingURL=NoopMeter.js.map - -/***/ }), - -/***/ 2647: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; -const NoopMeter_1 = __nccwpck_require__(4837); -/** - * An implementation of the {@link MeterProvider} which returns an impotent Meter - * for all calls to `getMeter` - */ -class NoopMeterProvider { - getMeter(_name, _version, _options) { - return NoopMeter_1.NOOP_METER; - } -} -exports.NoopMeterProvider = NoopMeterProvider; -exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); -//# sourceMappingURL=NoopMeterProvider.js.map - -/***/ }), - /***/ 9957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -48825,37 +48471,6 @@ __exportStar(__nccwpck_require__(9406), exports); /***/ }), -/***/ 7591: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.propagation = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const propagation_1 = __nccwpck_require__(9909); -/** Entrypoint for propagation API */ -exports.propagation = propagation_1.PropagationAPI.getInstance(); -//# sourceMappingURL=propagation-api.js.map - -/***/ }), - /***/ 2368: /***/ ((__unused_webpack_module, exports) => { @@ -48881,17 +48496,20 @@ exports.NoopTextMapPropagator = void 0; /** * No-op implementations of {@link TextMapPropagator}. */ -class NoopTextMapPropagator { +var NoopTextMapPropagator = /** @class */ (function () { + function NoopTextMapPropagator() { + } /** Noop inject function does nothing */ - inject(_context, _carrier) { } + NoopTextMapPropagator.prototype.inject = function (_context, _carrier) { }; /** Noop extract function does nothing and returns the input context */ - extract(context, _carrier) { + NoopTextMapPropagator.prototype.extract = function (context, _carrier) { return context; - } - fields() { + }; + NoopTextMapPropagator.prototype.fields = function () { return []; - } -} + }; + return NoopTextMapPropagator; +}()); exports.NoopTextMapPropagator = NoopTextMapPropagator; //# sourceMappingURL=NoopTextMapPropagator.js.map @@ -48920,13 +48538,13 @@ exports.NoopTextMapPropagator = NoopTextMapPropagator; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; exports.defaultTextMapGetter = { - get(carrier, key) { + get: function (carrier, key) { if (carrier == null) { return undefined; } return carrier[key]; }, - keys(carrier) { + keys: function (carrier) { if (carrier == null) { return []; } @@ -48934,7 +48552,7 @@ exports.defaultTextMapGetter = { }, }; exports.defaultTextMapSetter = { - set(carrier, key, value) { + set: function (carrier, key, value) { if (carrier == null) { return; } @@ -48945,37 +48563,6 @@ exports.defaultTextMapSetter = { /***/ }), -/***/ 8989: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.trace = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const trace_1 = __nccwpck_require__(1539); -/** Entrypoint for trace API */ -exports.trace = trace_1.TraceAPI.getInstance(); -//# sourceMappingURL=trace-api.js.map - -/***/ }), - /***/ 1462: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -48998,49 +48585,51 @@ exports.trace = trace_1.TraceAPI.getInstance(); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; -const invalid_span_constants_1 = __nccwpck_require__(1760); +var invalid_span_constants_1 = __nccwpck_require__(1760); /** * The NonRecordingSpan is the default {@link Span} that is used when no Span * implementation is available. All operations are no-op including context * propagation. */ -class NonRecordingSpan { - constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { +var NonRecordingSpan = /** @class */ (function () { + function NonRecordingSpan(_spanContext) { + if (_spanContext === void 0) { _spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT; } this._spanContext = _spanContext; } // Returns a SpanContext. - spanContext() { + NonRecordingSpan.prototype.spanContext = function () { return this._spanContext; - } + }; // By default does nothing - setAttribute(_key, _value) { + NonRecordingSpan.prototype.setAttribute = function (_key, _value) { return this; - } + }; // By default does nothing - setAttributes(_attributes) { + NonRecordingSpan.prototype.setAttributes = function (_attributes) { return this; - } + }; // By default does nothing - addEvent(_name, _attributes) { + NonRecordingSpan.prototype.addEvent = function (_name, _attributes) { return this; - } + }; // By default does nothing - setStatus(_status) { + NonRecordingSpan.prototype.setStatus = function (_status) { return this; - } + }; // By default does nothing - updateName(_name) { + NonRecordingSpan.prototype.updateName = function (_name) { return this; - } + }; // By default does nothing - end(_endTime) { } + NonRecordingSpan.prototype.end = function (_endTime) { }; // isRecording always returns false for NonRecordingSpan. - isRecording() { + NonRecordingSpan.prototype.isRecording = function () { return false; - } + }; // By default does nothing - recordException(_exception, _time) { } -} + NonRecordingSpan.prototype.recordException = function (_exception, _time) { }; + return NonRecordingSpan; +}()); exports.NonRecordingSpan = NonRecordingSpan; //# sourceMappingURL=NonRecordingSpan.js.map @@ -49068,34 +48657,36 @@ exports.NonRecordingSpan = NonRecordingSpan; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; -const context_1 = __nccwpck_require__(7171); -const context_utils_1 = __nccwpck_require__(3326); -const NonRecordingSpan_1 = __nccwpck_require__(1462); -const spancontext_utils_1 = __nccwpck_require__(9745); -const contextApi = context_1.ContextAPI.getInstance(); +var context_1 = __nccwpck_require__(7171); +var context_utils_1 = __nccwpck_require__(3326); +var NonRecordingSpan_1 = __nccwpck_require__(1462); +var spancontext_utils_1 = __nccwpck_require__(9745); +var context = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. */ -class NoopTracer { +var NoopTracer = /** @class */ (function () { + function NoopTracer() { + } // startSpan starts a noop span. - startSpan(name, options, context = contextApi.active()) { - const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + NoopTracer.prototype.startSpan = function (name, options, context) { + var root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan_1.NonRecordingSpan(); } - const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); + var parentFromContext = context && context_utils_1.getSpanContext(context); if (isSpanContext(parentFromContext) && - (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { + spancontext_utils_1.isSpanContextValid(parentFromContext)) { return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); } else { return new NonRecordingSpan_1.NonRecordingSpan(); } - } - startActiveSpan(name, arg2, arg3, arg4) { - let opts; - let ctx; - let fn; + }; + NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { + var opts; + var ctx; + var fn; if (arguments.length < 2) { return; } @@ -49111,12 +48702,13 @@ class NoopTracer { ctx = arg3; fn = arg4; } - const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); - const span = this.startSpan(name, opts, parentContext); - const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); - return contextApi.with(contextWithSpanSet, fn, undefined, span); - } -} + var parentContext = ctx !== null && ctx !== void 0 ? ctx : context.active(); + var span = this.startSpan(name, opts, parentContext); + var contextWithSpanSet = context_utils_1.setSpan(parentContext, span); + return context.with(contextWithSpanSet, fn, undefined, span); + }; + return NoopTracer; +}()); exports.NoopTracer = NoopTracer; function isSpanContext(spanContext) { return (typeof spanContext === 'object' && @@ -49150,18 +48742,21 @@ function isSpanContext(spanContext) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; -const NoopTracer_1 = __nccwpck_require__(7606); +var NoopTracer_1 = __nccwpck_require__(7606); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. * * All operations are no-op. */ -class NoopTracerProvider { - getTracer(_name, _version, _options) { - return new NoopTracer_1.NoopTracer(); +var NoopTracerProvider = /** @class */ (function () { + function NoopTracerProvider() { } -} + NoopTracerProvider.prototype.getTracer = function (_name, _version) { + return new NoopTracer_1.NoopTracer(); + }; + return NoopTracerProvider; +}()); exports.NoopTracerProvider = NoopTracerProvider; //# sourceMappingURL=NoopTracerProvider.js.map @@ -49189,41 +48784,41 @@ exports.NoopTracerProvider = NoopTracerProvider; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; -const NoopTracer_1 = __nccwpck_require__(7606); -const NOOP_TRACER = new NoopTracer_1.NoopTracer(); +var NoopTracer_1 = __nccwpck_require__(7606); +var NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider */ -class ProxyTracer { - constructor(_provider, name, version, options) { +var ProxyTracer = /** @class */ (function () { + function ProxyTracer(_provider, name, version) { this._provider = _provider; this.name = name; this.version = version; - this.options = options; } - startSpan(name, options, context) { + ProxyTracer.prototype.startSpan = function (name, options, context) { return this._getTracer().startSpan(name, options, context); - } - startActiveSpan(_name, _options, _context, _fn) { - const tracer = this._getTracer(); + }; + ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) { + var tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); - } + }; /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. */ - _getTracer() { + ProxyTracer.prototype._getTracer = function () { if (this._delegate) { return this._delegate; } - const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + var tracer = this._provider.getDelegateTracer(this.name, this.version); if (!tracer) { return NOOP_TRACER; } this._delegate = tracer; return this._delegate; - } -} + }; + return ProxyTracer; +}()); exports.ProxyTracer = ProxyTracer; //# sourceMappingURL=ProxyTracer.js.map @@ -49251,9 +48846,9 @@ exports.ProxyTracer = ProxyTracer; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; -const ProxyTracer_1 = __nccwpck_require__(3503); -const NoopTracerProvider_1 = __nccwpck_require__(3259); -const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); +var ProxyTracer_1 = __nccwpck_require__(3503); +var NoopTracerProvider_1 = __nccwpck_require__(3259); +var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. * @@ -49262,34 +48857,62 @@ const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); * When a delegate is set after tracers have already been provided, * all tracers already provided will use the provided delegate implementation. */ -class ProxyTracerProvider { +var ProxyTracerProvider = /** @class */ (function () { + function ProxyTracerProvider() { + } /** * Get a {@link ProxyTracer} */ - getTracer(name, version, options) { + ProxyTracerProvider.prototype.getTracer = function (name, version) { var _a; - return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); - } - getDelegate() { + return ((_a = this.getDelegateTracer(name, version)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version)); + }; + ProxyTracerProvider.prototype.getDelegate = function () { var _a; return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; - } + }; /** * Set the delegate tracer provider */ - setDelegate(delegate) { + ProxyTracerProvider.prototype.setDelegate = function (delegate) { this._delegate = delegate; - } - getDelegateTracer(name, version, options) { + }; + ProxyTracerProvider.prototype.getDelegateTracer = function (name, version) { var _a; - return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); - } -} + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version); + }; + return ProxyTracerProvider; +}()); exports.ProxyTracerProvider = ProxyTracerProvider; //# sourceMappingURL=ProxyTracerProvider.js.map /***/ }), +/***/ 9671: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=Sampler.js.map + +/***/ }), + /***/ 3209: /***/ ((__unused_webpack_module, exports) => { @@ -49313,7 +48936,6 @@ exports.ProxyTracerProvider = ProxyTracerProvider; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SamplingDecision = void 0; /** - * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. * A sampling decision that determines how a {@link Span} will be recorded * and collected. */ @@ -49339,6 +48961,56 @@ var SamplingDecision; /***/ }), +/***/ 955: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=SpanOptions.js.map + +/***/ }), + +/***/ 7492: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=attributes.js.map + +/***/ }), + /***/ 3326: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -49360,14 +49032,13 @@ var SamplingDecision; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; -const context_1 = __nccwpck_require__(8242); -const NonRecordingSpan_1 = __nccwpck_require__(1462); -const context_2 = __nccwpck_require__(7171); +exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0; +var context_1 = __nccwpck_require__(8242); +var NonRecordingSpan_1 = __nccwpck_require__(1462); /** * span key */ -const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); +var SPAN_KEY = context_1.createContextKey('OpenTelemetry Context Key SPAN'); /** * Return the span if one exists * @@ -49377,13 +49048,6 @@ function getSpan(context) { return context.getValue(SPAN_KEY) || undefined; } exports.getSpan = getSpan; -/** - * Gets the span from the current context, if one exists. - */ -function getActiveSpan() { - return getSpan(context_2.ContextAPI.getInstance().active()); -} -exports.getActiveSpan = getActiveSpan; /** * Set the span on a context * @@ -49428,7 +49092,7 @@ exports.getSpanContext = getSpanContext; /***/ }), -/***/ 2110: +/***/ 1760: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49449,96 +49113,20 @@ exports.getSpanContext = getSpanContext; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TraceStateImpl = void 0; -const tracestate_validators_1 = __nccwpck_require__(4864); -const MAX_TRACE_STATE_ITEMS = 32; -const MAX_TRACE_STATE_LEN = 512; -const LIST_MEMBERS_SEPARATOR = ','; -const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; -/** - * TraceState must be a class and not a simple object type because of the spec - * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). - * - * Here is the list of allowed mutations: - * - New key-value pair should be added into the beginning of the list - * - The value of any key can be updated. Modified keys MUST be moved to the - * beginning of the list. - */ -class TraceStateImpl { - constructor(rawTraceState) { - this._internalState = new Map(); - if (rawTraceState) - this._parse(rawTraceState); - } - set(key, value) { - // TODO: Benchmark the different approaches(map vs list) and - // use the faster one. - const traceState = this._clone(); - if (traceState._internalState.has(key)) { - traceState._internalState.delete(key); - } - traceState._internalState.set(key, value); - return traceState; - } - unset(key) { - const traceState = this._clone(); - traceState._internalState.delete(key); - return traceState; - } - get(key) { - return this._internalState.get(key); - } - serialize() { - return this._keys() - .reduce((agg, key) => { - agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); - return agg; - }, []) - .join(LIST_MEMBERS_SEPARATOR); - } - _parse(rawTraceState) { - if (rawTraceState.length > MAX_TRACE_STATE_LEN) - return; - this._internalState = rawTraceState - .split(LIST_MEMBERS_SEPARATOR) - .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning - .reduce((agg, part) => { - const listMember = part.trim(); // Optional Whitespace (OWS) handling - const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); - if (i !== -1) { - const key = listMember.slice(0, i); - const value = listMember.slice(i + 1, part.length); - if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { - agg.set(key, value); - } - else { - // TODO: Consider to add warning log - } - } - return agg; - }, new Map()); - // Because of the reverse() requirement, trunc must be done after map is created - if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { - this._internalState = new Map(Array.from(this._internalState.entries()) - .reverse() // Use reverse same as original tracestate parse chain - .slice(0, MAX_TRACE_STATE_ITEMS)); - } - } - _keys() { - return Array.from(this._internalState.keys()).reverse(); - } - _clone() { - const traceState = new TraceStateImpl(); - traceState._internalState = new Map(this._internalState); - return traceState; - } -} -exports.TraceStateImpl = TraceStateImpl; -//# sourceMappingURL=tracestate-impl.js.map +exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +var trace_flags_1 = __nccwpck_require__(6905); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map /***/ }), -/***/ 4864: +/***/ 4023: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49559,40 +49147,12 @@ exports.TraceStateImpl = TraceStateImpl; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateValue = exports.validateKey = void 0; -const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; -const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; -const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; -const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); -const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; -const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; -/** - * Key is opaque string up to 256 characters printable. It MUST begin with a - * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, - * underscores _, dashes -, asterisks *, and forward slashes /. - * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the - * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. - * see https://www.w3.org/TR/trace-context/#key - */ -function validateKey(key) { - return VALID_KEY_REGEX.test(key); -} -exports.validateKey = validateKey; -/** - * Value is opaque string up to 256 characters printable ASCII RFC0020 - * characters (i.e., the range 0x20 to 0x7E) except comma , and =. - */ -function validateValue(value) { - return (VALID_VALUE_BASE_REGEX.test(value) && - !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); -} -exports.validateValue = validateValue; -//# sourceMappingURL=tracestate-validators.js.map +//# sourceMappingURL=link.js.map /***/ }), -/***/ 2615: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4416: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49612,18 +49172,12 @@ exports.validateValue = validateValue; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createTraceState = void 0; -const tracestate_impl_1 = __nccwpck_require__(2110); -function createTraceState(rawTraceState) { - return new tracestate_impl_1.TraceStateImpl(rawTraceState); -} -exports.createTraceState = createTraceState; -//# sourceMappingURL=utils.js.map +//# sourceMappingURL=span.js.map /***/ }), -/***/ 1760: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5769: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49643,16 +49197,7 @@ exports.createTraceState = createTraceState; * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -const trace_flags_1 = __nccwpck_require__(6905); -exports.INVALID_SPANID = '0000000000000000'; -exports.INVALID_TRACEID = '00000000000000000000000000000000'; -exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, -}; -//# sourceMappingURL=invalid-span-constants.js.map +//# sourceMappingURL=span_context.js.map /***/ }), @@ -49731,10 +49276,10 @@ exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = e * See the License for the specific language governing permissions and * limitations under the License. */ -const invalid_span_constants_1 = __nccwpck_require__(1760); -const NonRecordingSpan_1 = __nccwpck_require__(1462); -const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; -const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +var invalid_span_constants_1 = __nccwpck_require__(1760); +var NonRecordingSpan_1 = __nccwpck_require__(1462); +var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; } @@ -49828,6 +49373,81 @@ var TraceFlags; /***/ }), +/***/ 8384: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=trace_state.js.map + +/***/ }), + +/***/ 3168: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=tracer.js.map + +/***/ }), + +/***/ 891: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=tracer_provider.js.map + +/***/ }), + /***/ 8996: /***/ ((__unused_webpack_module, exports) => { @@ -49851,7 +49471,7 @@ var TraceFlags; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.4.1'; +exports.VERSION = '1.0.4'; //# sourceMappingURL=version.js.map /***/ }), @@ -71596,7 +71216,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerVersion = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerVersion = exports.getPackageManagerCommandOutput = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -71639,8 +71259,10 @@ const getPackageManagerWorkingDir = () => { return cacheDependencyPath ? path_1.default.dirname(cacheDependencyPath) : null; }; exports.getPackageManagerWorkingDir = getPackageManagerWorkingDir; +const getPackageManagerCommandOutput = (command) => exports.getCommandOutput(command, exports.getPackageManagerWorkingDir()); +exports.getPackageManagerCommandOutput = getPackageManagerCommandOutput; const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`, exports.getPackageManagerWorkingDir()); + const stdOut = yield exports.getPackageManagerCommandOutput(`${packageManager} ${command}`); if (!stdOut) { throw new Error(`Could not retrieve version of ${packageManager}`); } @@ -71670,7 +71292,7 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void }); exports.getPackageManagerInfo = getPackageManagerInfo; const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand, exports.getPackageManagerWorkingDir()); + const stdOut = yield exports.getPackageManagerCommandOutput(packageManagerInfo.getCacheFolderCommand); if (!stdOut) { throw new Error(`Could not get cache folder path for ${packageManager}`); } diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 804768a64..d2e858e92 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -61,13 +61,15 @@ export const getPackageManagerWorkingDir = (): string | null => { return cacheDependencyPath ? path.dirname(cacheDependencyPath) : null; }; +export const getPackageManagerCommandOutput = (command: string) => + getCommandOutput(command, getPackageManagerWorkingDir()); + export const getPackageManagerVersion = async ( packageManager: string, command: string ) => { - const stdOut = await getCommandOutput( - `${packageManager} ${command}`, - getPackageManagerWorkingDir() + const stdOut = await getPackageManagerCommandOutput( + `${packageManager} ${command}` ); if (!stdOut) { @@ -101,9 +103,8 @@ export const getCacheDirectoryPath = async ( packageManagerInfo: PackageManagerInfo, packageManager: string ) => { - const stdOut = await getCommandOutput( - packageManagerInfo.getCacheFolderCommand, - getPackageManagerWorkingDir() + const stdOut = await getPackageManagerCommandOutput( + packageManagerInfo.getCacheFolderCommand ); if (!stdOut) { From a3d2aaf78fb14d834aa9a035aab0170fae2e36c6 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Thu, 4 May 2023 16:05:46 +0200 Subject: [PATCH 08/21] handle non-dir cache-dependency-path --- __tests__/authutil.test.ts | 144 ++++++++++++++++++++++--------------- dist/cache-save/index.js | 10 ++- dist/setup/index.js | 12 +++- src/cache-restore.ts | 4 +- src/cache-utils.ts | 13 +++- 5 files changed, 120 insertions(+), 63 deletions(-) diff --git a/__tests__/authutil.test.ts b/__tests__/authutil.test.ts index cc1c74788..a9b1dd043 100644 --- a/__tests__/authutil.test.ts +++ b/__tests__/authutil.test.ts @@ -1,11 +1,10 @@ import os from 'os'; -import * as fs from 'fs'; +import fs from 'fs'; import * as path from 'path'; import * as core from '@actions/core'; import * as io from '@actions/io'; import * as auth from '../src/authutil'; import * as cacheUtils from '../src/cache-utils'; -import {getCacheDirectoryPath} from '../src/cache-utils'; let rcFile: string; @@ -212,65 +211,96 @@ describe('authutil tests', () => { ); }); - it('getPackageManagerWorkingDir should return null for not yarn', async () => { - process.env['INPUT_CACHE'] = 'some'; - delete process.env['INPUT_CACHE-DEPENDENCY-PATH']; - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toBeNull(); - }); + describe('getPackageManagerWorkingDir', () => { + let existsSpy: jest.SpyInstance; + let lstatSpy: jest.SpyInstance; - it('getPackageManagerWorkingDir should return null for not yarn with cache-dependency-path', async () => { - process.env['INPUT_CACHE'] = 'some'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = '/foo/bar'; - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toBeNull(); - }); + beforeEach(() => { + existsSpy = jest.spyOn(fs, 'existsSync'); + existsSpy.mockImplementation(() => true); - it('getPackageManagerWorkingDir should return null for yarn but without cache-dependency-path', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - delete process.env['INPUT_CACHE-DEPENDENCY-PATH']; - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toBeNull(); - }); + lstatSpy = jest.spyOn(fs, 'lstatSync'); + lstatSpy.mockImplementation(arg => ({ + isDirectory: () => true + })); + }); - it('getPackageManagerWorkingDir should return path for yarn with cache-dependency-path', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - const cachePath = '/foo/bar'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toEqual(path.dirname(cachePath)); - }); + afterEach(() => { + existsSpy.mockRestore(); + lstatSpy.mockRestore(); + }); - it('getCommandOutput(getPackageManagerVersion) should be called from with getPackageManagerWorkingDir result', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - const cachePath = '/foo/bar'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; - const getCommandOutputSpy = jest - .spyOn(cacheUtils, 'getCommandOutput') - .mockReturnValue(Promise.resolve('baz')); - - const version = await cacheUtils.getPackageManagerVersion('foo', 'bar'); - expect(getCommandOutputSpy).toHaveBeenCalledWith( - `foo bar`, - path.dirname(cachePath) - ); - }); + it('getPackageManagerWorkingDir should return null for not yarn', async () => { + process.env['INPUT_CACHE'] = 'some'; + delete process.env['INPUT_CACHE-DEPENDENCY-PATH']; + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toBeNull(); + }); - it('getCommandOutput(getCacheDirectoryPath) should be called from with getPackageManagerWorkingDir result', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - const cachePath = '/foo/bar'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; - const getCommandOutputSpy = jest - .spyOn(cacheUtils, 'getCommandOutput') - .mockReturnValue(Promise.resolve('baz')); - - const version = await cacheUtils.getCacheDirectoryPath( - {lockFilePatterns: [], getCacheFolderCommand: 'quz'}, - '' - ); - expect(getCommandOutputSpy).toHaveBeenCalledWith( - `quz`, - path.dirname(cachePath) - ); + it('getPackageManagerWorkingDir should return null for not yarn with cache-dependency-path', async () => { + process.env['INPUT_CACHE'] = 'some'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = '/foo/bar'; + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toBeNull(); + }); + + it('getPackageManagerWorkingDir should return null for yarn but without cache-dependency-path', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + delete process.env['INPUT_CACHE-DEPENDENCY-PATH']; + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toBeNull(); + }); + + it('getPackageManagerWorkingDir should return null for yarn with cache-dependency-path for not-existing directory', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + const cachePath = '/foo/bar'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; + lstatSpy.mockImplementation(arg => ({ + isDirectory: () => false + })); + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toBeNull(); + }); + + it('getPackageManagerWorkingDir should return path for yarn with cache-dependency-path', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + const cachePath = '/foo/bar'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; + const dir = cacheUtils.getPackageManagerWorkingDir(); + expect(dir).toEqual(path.dirname(cachePath)); + }); + + it('getCommandOutput(getPackageManagerVersion) should be called from with getPackageManagerWorkingDir result', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + const cachePath = '/foo/bar'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; + const getCommandOutputSpy = jest + .spyOn(cacheUtils, 'getCommandOutput') + .mockReturnValue(Promise.resolve('baz')); + + const version = await cacheUtils.getPackageManagerVersion('foo', 'bar'); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + `foo bar`, + path.dirname(cachePath) + ); + }); + + it('getCommandOutput(getCacheDirectoryPath) should be called from with getPackageManagerWorkingDir result', async () => { + process.env['INPUT_CACHE'] = 'yarn'; + const cachePath = '/foo/bar'; + process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; + const getCommandOutputSpy = jest + .spyOn(cacheUtils, 'getCommandOutput') + .mockReturnValue(Promise.resolve('baz')); + + const version = await cacheUtils.getCacheDirectoryPath( + {lockFilePatterns: [], getCacheFolderCommand: 'quz'}, + '' + ); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + `quz`, + path.dirname(cachePath) + ); + }); }); }); diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 6a0ff626b..aad770848 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -59253,6 +59253,7 @@ const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); const path_1 = __importDefault(__nccwpck_require__(1017)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); exports.supportedPackageManagers = { npm: { lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], @@ -59288,7 +59289,14 @@ const getPackageManagerWorkingDir = () => { return null; } const cacheDependencyPath = core.getInput('cache-dependency-path'); - return cacheDependencyPath ? path_1.default.dirname(cacheDependencyPath) : null; + if (!cacheDependencyPath) { + return null; + } + const wd = path_1.default.dirname(cacheDependencyPath); + if (fs_1.default.existsSync(wd) && fs_1.default.lstatSync(wd).isDirectory()) { + return wd; + } + return null; }; exports.getPackageManagerWorkingDir = getPackageManagerWorkingDir; const getPackageManagerCommandOutput = (command) => exports.getCommandOutput(command, exports.getPackageManagerWorkingDir()); diff --git a/dist/setup/index.js b/dist/setup/index.js index bb5ac4647..c6d970eaa 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71167,7 +71167,7 @@ const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, exports.restoreCache = restoreCache; const findLockFile = (packageManager) => { const lockFiles = packageManager.lockFilePatterns; - const workspace = cache_utils_1.getPackageManagerWorkingDir() || process.env.GITHUB_WORKSPACE; + const workspace = process.env.GITHUB_WORKSPACE; const rootContent = fs_1.default.readdirSync(workspace); const lockFile = lockFiles.find(item => rootContent.includes(item)); if (!lockFile) { @@ -71221,6 +71221,7 @@ const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); const path_1 = __importDefault(__nccwpck_require__(1017)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); exports.supportedPackageManagers = { npm: { lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], @@ -71256,7 +71257,14 @@ const getPackageManagerWorkingDir = () => { return null; } const cacheDependencyPath = core.getInput('cache-dependency-path'); - return cacheDependencyPath ? path_1.default.dirname(cacheDependencyPath) : null; + if (!cacheDependencyPath) { + return null; + } + const wd = path_1.default.dirname(cacheDependencyPath); + if (fs_1.default.existsSync(wd) && fs_1.default.lstatSync(wd).isDirectory()) { + return wd; + } + return null; }; exports.getPackageManagerWorkingDir = getPackageManagerWorkingDir; const getPackageManagerCommandOutput = (command) => exports.getCommandOutput(command, exports.getPackageManagerWorkingDir()); diff --git a/src/cache-restore.ts b/src/cache-restore.ts index 733e486a8..c7317270e 100644 --- a/src/cache-restore.ts +++ b/src/cache-restore.ts @@ -56,8 +56,8 @@ export const restoreCache = async ( const findLockFile = (packageManager: PackageManagerInfo) => { const lockFiles = packageManager.lockFilePatterns; - const workspace = - getPackageManagerWorkingDir() || process.env.GITHUB_WORKSPACE!; + const workspace = process.env.GITHUB_WORKSPACE!; + const rootContent = fs.readdirSync(workspace); const lockFile = lockFiles.find(item => rootContent.includes(item)); diff --git a/src/cache-utils.ts b/src/cache-utils.ts index d2e858e92..ebd5144b1 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -2,6 +2,7 @@ import * as core from '@actions/core'; import * as exec from '@actions/exec'; import * as cache from '@actions/cache'; import path from 'path'; +import fs from 'fs'; type SupportedPackageManagers = { [prop: string]: PackageManagerInfo; @@ -58,7 +59,17 @@ export const getPackageManagerWorkingDir = (): string | null => { } const cacheDependencyPath = core.getInput('cache-dependency-path'); - return cacheDependencyPath ? path.dirname(cacheDependencyPath) : null; + if (!cacheDependencyPath) { + return null; + } + + const wd = path.dirname(cacheDependencyPath); + + if (fs.existsSync(wd) && fs.lstatSync(wd).isDirectory()) { + return wd; + } + + return null; }; export const getPackageManagerCommandOutput = (command: string) => From d836439c6a04836ef0186240e4ec5def7d250fdd Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Thu, 4 May 2023 16:35:25 +0200 Subject: [PATCH 09/21] bump cache version --- __tests__/cache-restore.test.ts | 2 +- dist/setup/index.js | 2 +- src/cache-restore.ts | 3 +-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/__tests__/cache-restore.test.ts b/__tests__/cache-restore.test.ts index df9170ad2..59135452c 100644 --- a/__tests__/cache-restore.test.ts +++ b/__tests__/cache-restore.test.ts @@ -135,7 +135,7 @@ describe('cache-restore', () => { await restoreCache(packageManager); expect(hashFilesSpy).toHaveBeenCalled(); expect(infoSpy).toHaveBeenCalledWith( - `Cache restored from key: node-cache-${platform}-${packageManager}-${fileHash}` + `Cache restored from key: node-cache-${platform}-${packageManager}-v2-${fileHash}` ); expect(infoSpy).not.toHaveBeenCalledWith( `${packageManager} cache is not found` diff --git a/dist/setup/index.js b/dist/setup/index.js index c6d970eaa..eae17a848 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71152,7 +71152,7 @@ const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, if (!fileHash) { throw new Error('Some specified paths were not resolved, unable to cache dependencies.'); } - const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; + const primaryKey = `node-cache-${platform}-${packageManager}-v2-${fileHash}`; core.debug(`primary key is ${primaryKey}`); core.saveState(constants_1.State.CachePrimaryKey, primaryKey); const cacheKey = yield cache.restoreCache([cachePath], primaryKey); diff --git a/src/cache-restore.ts b/src/cache-restore.ts index c7317270e..0341c109f 100644 --- a/src/cache-restore.ts +++ b/src/cache-restore.ts @@ -8,7 +8,6 @@ import {State} from './constants'; import { getCacheDirectoryPath, getPackageManagerInfo, - getPackageManagerWorkingDir, PackageManagerInfo } from './cache-utils'; @@ -37,7 +36,7 @@ export const restoreCache = async ( ); } - const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; + const primaryKey = `node-cache-${platform}-${packageManager}-v2-${fileHash}`; core.debug(`primary key is ${primaryKey}`); core.saveState(State.CachePrimaryKey, primaryKey); From 2b97a8fb237a02e5eb297969e0470517227df8d5 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Mon, 8 May 2023 18:56:18 +0200 Subject: [PATCH 10/21] run checks From 914a8e9bcc458c1e2a82e1eb0413590386cefa02 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Thu, 11 May 2023 09:40:44 +0200 Subject: [PATCH 11/21] Handle globs in cacheDependencyPath --- __tests__/authutil.test.ts | 93 --- __tests__/cache-restore.test.ts | 14 +- __tests__/cache-save.test.ts | 16 +- __tests__/cache-utils.test.ts | 295 ++++++- __tests__/mock/glob-mock.test.ts | 18 + __tests__/mock/glob-mock.ts | 29 + dist/cache-save/index.js | 1322 ++++++++++++++++++++++++++++-- dist/setup/index.js | 124 +-- src/cache-restore.ts | 10 +- src/cache-save.ts | 15 +- src/cache-utils.ts | 208 +++-- 11 files changed, 1853 insertions(+), 291 deletions(-) create mode 100644 __tests__/mock/glob-mock.test.ts create mode 100644 __tests__/mock/glob-mock.ts diff --git a/__tests__/authutil.test.ts b/__tests__/authutil.test.ts index a9b1dd043..0676a8506 100644 --- a/__tests__/authutil.test.ts +++ b/__tests__/authutil.test.ts @@ -210,97 +210,4 @@ describe('authutil tests', () => { `@otherscope:registry=MMM${os.EOL}//registry.npmjs.org/:_authToken=\${NODE_AUTH_TOKEN}${os.EOL}@myscope:registry=https://registry.npmjs.org/${os.EOL}always-auth=true` ); }); - - describe('getPackageManagerWorkingDir', () => { - let existsSpy: jest.SpyInstance; - let lstatSpy: jest.SpyInstance; - - beforeEach(() => { - existsSpy = jest.spyOn(fs, 'existsSync'); - existsSpy.mockImplementation(() => true); - - lstatSpy = jest.spyOn(fs, 'lstatSync'); - lstatSpy.mockImplementation(arg => ({ - isDirectory: () => true - })); - }); - - afterEach(() => { - existsSpy.mockRestore(); - lstatSpy.mockRestore(); - }); - - it('getPackageManagerWorkingDir should return null for not yarn', async () => { - process.env['INPUT_CACHE'] = 'some'; - delete process.env['INPUT_CACHE-DEPENDENCY-PATH']; - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toBeNull(); - }); - - it('getPackageManagerWorkingDir should return null for not yarn with cache-dependency-path', async () => { - process.env['INPUT_CACHE'] = 'some'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = '/foo/bar'; - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toBeNull(); - }); - - it('getPackageManagerWorkingDir should return null for yarn but without cache-dependency-path', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - delete process.env['INPUT_CACHE-DEPENDENCY-PATH']; - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toBeNull(); - }); - - it('getPackageManagerWorkingDir should return null for yarn with cache-dependency-path for not-existing directory', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - const cachePath = '/foo/bar'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; - lstatSpy.mockImplementation(arg => ({ - isDirectory: () => false - })); - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toBeNull(); - }); - - it('getPackageManagerWorkingDir should return path for yarn with cache-dependency-path', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - const cachePath = '/foo/bar'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; - const dir = cacheUtils.getPackageManagerWorkingDir(); - expect(dir).toEqual(path.dirname(cachePath)); - }); - - it('getCommandOutput(getPackageManagerVersion) should be called from with getPackageManagerWorkingDir result', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - const cachePath = '/foo/bar'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; - const getCommandOutputSpy = jest - .spyOn(cacheUtils, 'getCommandOutput') - .mockReturnValue(Promise.resolve('baz')); - - const version = await cacheUtils.getPackageManagerVersion('foo', 'bar'); - expect(getCommandOutputSpy).toHaveBeenCalledWith( - `foo bar`, - path.dirname(cachePath) - ); - }); - - it('getCommandOutput(getCacheDirectoryPath) should be called from with getPackageManagerWorkingDir result', async () => { - process.env['INPUT_CACHE'] = 'yarn'; - const cachePath = '/foo/bar'; - process.env['INPUT_CACHE-DEPENDENCY-PATH'] = cachePath; - const getCommandOutputSpy = jest - .spyOn(cacheUtils, 'getCommandOutput') - .mockReturnValue(Promise.resolve('baz')); - - const version = await cacheUtils.getCacheDirectoryPath( - {lockFilePatterns: [], getCacheFolderCommand: 'quz'}, - '' - ); - expect(getCommandOutputSpy).toHaveBeenCalledWith( - `quz`, - path.dirname(cachePath) - ); - }); - }); }); diff --git a/__tests__/cache-restore.test.ts b/__tests__/cache-restore.test.ts index 59135452c..ba20a22d8 100644 --- a/__tests__/cache-restore.test.ts +++ b/__tests__/cache-restore.test.ts @@ -32,13 +32,13 @@ describe('cache-restore', () => { function findCacheFolder(command: string) { switch (command) { - case utils.supportedPackageManagers.npm.getCacheFolderCommand: + case utils.npmGetCacheFolderCommand: return npmCachePath; - case utils.supportedPackageManagers.pnpm.getCacheFolderCommand: + case utils.pnpmGetCacheFolderCommand: return pnpmCachePath; - case utils.supportedPackageManagers.yarn1.getCacheFolderCommand: + case utils.yarn1GetCacheFolderCommand: return yarn1CachePath; - case utils.supportedPackageManagers.yarn2.getCacheFolderCommand: + case utils.yarn2GetCacheFolderCommand: return yarn2CachePath; default: return 'packge/not/found'; @@ -108,7 +108,7 @@ describe('cache-restore', () => { it.each([['npm7'], ['npm6'], ['pnpm6'], ['yarn1'], ['yarn2'], ['random']])( 'Throw an error because %s is not supported', async packageManager => { - await expect(restoreCache(packageManager)).rejects.toThrow( + await expect(restoreCache(packageManager, '')).rejects.toThrow( `Caching for '${packageManager}' is not supported` ); } @@ -132,7 +132,7 @@ describe('cache-restore', () => { } }); - await restoreCache(packageManager); + await restoreCache(packageManager, ''); expect(hashFilesSpy).toHaveBeenCalled(); expect(infoSpy).toHaveBeenCalledWith( `Cache restored from key: node-cache-${platform}-${packageManager}-v2-${fileHash}` @@ -163,7 +163,7 @@ describe('cache-restore', () => { }); restoreCacheSpy.mockImplementationOnce(() => undefined); - await restoreCache(packageManager); + await restoreCache(packageManager, ''); expect(hashFilesSpy).toHaveBeenCalled(); expect(infoSpy).toHaveBeenCalledWith( `${packageManager} cache is not found` diff --git a/__tests__/cache-save.test.ts b/__tests__/cache-save.test.ts index f96cde5a4..0651138e3 100644 --- a/__tests__/cache-save.test.ts +++ b/__tests__/cache-save.test.ts @@ -117,7 +117,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); - expect(debugSpy).toHaveBeenCalledWith(`yarn path is ${commonPath}/yarn1`); + expect(debugSpy).toHaveBeenCalledWith( + 'yarn path is /some/random/path/yarn1 (derived from cache-dependency-path: "")' + ); expect(debugSpy).toHaveBeenCalledWith('Consumed yarn version is 1.2.3'); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` @@ -137,7 +139,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); - expect(debugSpy).toHaveBeenCalledWith(`yarn path is ${commonPath}/yarn2`); + expect(debugSpy).toHaveBeenCalledWith( + 'yarn path is /some/random/path/yarn2 (derived from cache-dependency-path: "")' + ); expect(debugSpy).toHaveBeenCalledWith('Consumed yarn version is 2.2.3'); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` @@ -199,7 +203,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); - expect(debugSpy).toHaveBeenCalledWith(`yarn path is ${commonPath}/yarn1`); + expect(debugSpy).toHaveBeenCalledWith( + 'yarn path is /some/random/path/yarn1 (derived from cache-dependency-path: "")' + ); expect(debugSpy).toHaveBeenCalledWith('Consumed yarn version is 1.2.3'); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` @@ -229,7 +235,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); - expect(debugSpy).toHaveBeenCalledWith(`yarn path is ${commonPath}/yarn2`); + expect(debugSpy).toHaveBeenCalledWith( + 'yarn path is /some/random/path/yarn2 (derived from cache-dependency-path: "")' + ); expect(debugSpy).toHaveBeenCalledWith('Consumed yarn version is 2.2.3'); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` diff --git a/__tests__/cache-utils.test.ts b/__tests__/cache-utils.test.ts index 9e8d653de..80e4a0844 100644 --- a/__tests__/cache-utils.test.ts +++ b/__tests__/cache-utils.test.ts @@ -2,7 +2,18 @@ import * as core from '@actions/core'; import * as cache from '@actions/cache'; import path from 'path'; import * as utils from '../src/cache-utils'; -import {PackageManagerInfo, isCacheFeatureAvailable} from '../src/cache-utils'; +import { + PackageManagerInfo, + isCacheFeatureAvailable, + supportedPackageManagers, + getCommandOutput, + expandCacheDependencyPath +} from '../src/cache-utils'; +import fs from 'fs'; +import * as cacheUtils from '../src/cache-utils'; +import * as glob from '@actions/glob'; +import {Globber} from '@actions/glob'; +import {MockGlobber} from './mock/glob-mock'; describe('cache-utils', () => { const versionYarn1 = '1.2.3'; @@ -30,7 +41,7 @@ describe('cache-utils', () => { it.each<[string, PackageManagerInfo | null]>([ ['npm', utils.supportedPackageManagers.npm], ['pnpm', utils.supportedPackageManagers.pnpm], - ['yarn', utils.supportedPackageManagers.yarn1], + ['yarn', utils.supportedPackageManagers.yarn], ['yarn1', null], ['yarn2', null], ['npm7', null] @@ -72,4 +83,284 @@ describe('cache-utils', () => { jest.resetAllMocks(); jest.clearAllMocks(); }); + + describe('getCacheDirectoriesPaths', () => { + let existsSpy: jest.SpyInstance; + let lstatSpy: jest.SpyInstance; + let globCreateSpy: jest.SpyInstance; + + beforeEach(() => { + existsSpy = jest.spyOn(fs, 'existsSync'); + existsSpy.mockImplementation(() => true); + + lstatSpy = jest.spyOn(fs, 'lstatSync'); + lstatSpy.mockImplementation(arg => ({ + isDirectory: () => true + })); + + globCreateSpy = jest.spyOn(glob, 'create'); + + globCreateSpy.mockImplementation( + (pattern: string): Promise => + MockGlobber.create(['/foo', '/bar']) + ); + }); + + afterEach(() => { + existsSpy.mockRestore(); + lstatSpy.mockRestore(); + globCreateSpy.mockRestore(); + }); + + it('expandCacheDependencyPath should handle one line', async () => { + expect(await expandCacheDependencyPath('one')).toEqual(['one']); + }); + + it('expandCacheDependencyPath should handle one line glob', async () => { + globCreateSpy.mockImplementation( + (pattern: string): Promise => + MockGlobber.create(['one', 'two']) + ); + expect(await expandCacheDependencyPath('**')).toEqual(['one', 'two']); + }); + + it('expandCacheDependencyPath should handle multiple lines', async () => { + const lines = ` + one +two + + `; + expect(await expandCacheDependencyPath(lines)).toEqual(['one', 'two']); + }); + + it('expandCacheDependencyPath should handle multiple globs', async () => { + const lines = ` + one +** + + `; + globCreateSpy.mockImplementation( + (pattern: string): Promise => + MockGlobber.create(['two', 'three']) + ); + expect(await expandCacheDependencyPath(lines)).toEqual([ + 'one', + 'two', + 'three' + ]); + }); + + it.each([ + [supportedPackageManagers.npm, ''], + [supportedPackageManagers.npm, '/dir/file.lock'], + [supportedPackageManagers.npm, '/**/file.lock'], + [supportedPackageManagers.pnpm, ''], + [supportedPackageManagers.pnpm, '/dir/file.lock'], + [supportedPackageManagers.pnpm, '/**/file.lock'] + ])( + 'getCacheDirectoriesPaths should return one dir for non yarn', + async (packageManagerInfo, cacheDependency) => { + getCommandOutputSpy.mockImplementation(() => 'foo'); + + const dirs = await cacheUtils.getCacheDirectoriesPaths( + packageManagerInfo, + cacheDependency + ); + expect(dirs).toEqual(['foo']); + // to do not call for a version + // call once for get cache folder + expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); + } + ); + + it('getCacheDirectoriesPaths should return one dir for yarn without cacheDependency', async () => { + getCommandOutputSpy.mockImplementation(() => 'foo'); + + const dirs = await cacheUtils.getCacheDirectoriesPaths( + supportedPackageManagers.yarn, + '' + ); + expect(dirs).toEqual(['foo']); + }); + + it.each([ + [supportedPackageManagers.npm, ''], + [supportedPackageManagers.npm, '/dir/file.lock'], + [supportedPackageManagers.npm, '/**/file.lock'], + [supportedPackageManagers.pnpm, ''], + [supportedPackageManagers.pnpm, '/dir/file.lock'], + [supportedPackageManagers.pnpm, '/**/file.lock'], + [supportedPackageManagers.yarn, ''], + [supportedPackageManagers.yarn, '/dir/file.lock'], + [supportedPackageManagers.yarn, '/**/file.lock'] + ])( + 'getCacheDirectoriesPaths should return empty array of folder in case of error', + async (packageManagerInfo, cacheDependency) => { + getCommandOutputSpy.mockImplementation((command: string) => + // return empty string to indicate getCacheFolderPath failed + // --version still works + command.includes('version') ? '1.' : '' + ); + lstatSpy.mockImplementation(arg => ({ + isDirectory: () => false + })); + + await expect( + cacheUtils.getCacheDirectoriesPaths( + packageManagerInfo, + cacheDependency + ) + ).rejects.toThrow(); //'Could not get cache folder path for /dir'); + } + ); + + it.each(['1.1.1', '2.2.2'])( + 'getCacheDirectoriesPaths yarn v%s should return one dir without cacheDependency', + async version => { + getCommandOutputSpy.mockImplementationOnce(() => version); + getCommandOutputSpy.mockImplementationOnce(() => `foo${version}`); + + const dirs = await cacheUtils.getCacheDirectoriesPaths( + supportedPackageManagers.yarn, + '' + ); + expect(dirs).toEqual([`foo${version}`]); + } + ); + + it.each(['1.1.1', '2.2.2'])( + 'getCacheDirectoriesPaths yarn v%s should return 2 dirs with globbed cacheDependency', + async version => { + let dirNo = 1; + getCommandOutputSpy.mockImplementation((command: string) => + command.includes('version') ? version : `file_${version}_${dirNo++}` + ); + globCreateSpy.mockImplementation( + (pattern: string): Promise => + MockGlobber.create(['/tmp/dir1/file', '/tmp/dir2/file']) + ); + + const dirs = await cacheUtils.getCacheDirectoriesPaths( + supportedPackageManagers.yarn, + '/tmp/**/file' + ); + expect(dirs).toEqual([`file_${version}_1`, `file_${version}_2`]); + } + ); + + // TODO: by design - glob is not expected to return duplicates so 3 patterns do not collapse to 2 + it.each(['1.1.1', '2.2.2'])( + 'getCacheDirectoriesPaths yarn v%s should return 3 dirs with globbed cacheDependency expanding to duplicates', + async version => { + let dirNo = 1; + getCommandOutputSpy.mockImplementation((command: string) => + command.includes('version') ? version : `file_${version}_${dirNo++}` + ); + globCreateSpy.mockImplementation( + (pattern: string): Promise => + MockGlobber.create([ + '/tmp/dir1/file', + '/tmp/dir2/file', + '/tmp/dir1/file' + ]) + ); + + const dirs = await cacheUtils.getCacheDirectoriesPaths( + supportedPackageManagers.yarn, + '/tmp/**/file' + ); + expect(dirs).toEqual([ + `file_${version}_1`, + `file_${version}_2`, + `file_${version}_3` + ]); + } + ); + + it.each(['1.1.1', '2.2.2'])( + 'getCacheDirectoriesPaths yarn v%s should return 2 uniq dirs despite duplicate cache directories', + async version => { + let dirNo = 1; + getCommandOutputSpy.mockImplementation((command: string) => + command.includes('version') + ? version + : `file_${version}_${dirNo++ % 2}` + ); + globCreateSpy.mockImplementation( + (pattern: string): Promise => + MockGlobber.create([ + '/tmp/dir1/file', + '/tmp/dir2/file', + '/tmp/dir3/file' + ]) + ); + + const dirs = await cacheUtils.getCacheDirectoriesPaths( + supportedPackageManagers.yarn, + '/tmp/**/file' + ); + expect(dirs).toEqual([`file_${version}_1`, `file_${version}_0`]); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(6); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + 'yarn --version', + '/tmp/dir1' + ); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + 'yarn --version', + '/tmp/dir2' + ); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + 'yarn --version', + '/tmp/dir3' + ); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + version.startsWith('1.') + ? 'yarn cache dir' + : 'yarn config get cacheFolder', + '/tmp/dir1' + ); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + version.startsWith('1.') + ? 'yarn cache dir' + : 'yarn config get cacheFolder', + '/tmp/dir2' + ); + expect(getCommandOutputSpy).toHaveBeenCalledWith( + version.startsWith('1.') + ? 'yarn cache dir' + : 'yarn config get cacheFolder', + '/tmp/dir3' + ); + } + ); + + it.each(['1.1.1', '2.2.2'])( + 'getCacheDirectoriesPaths yarn v%s should return 4 dirs with multiple globs', + async version => { + // simulate wrong indents + const cacheDependencyPath = `/tmp/dir1/file + /tmp/dir2/file +/tmp/**/file + `; + globCreateSpy.mockImplementation( + (pattern: string): Promise => + MockGlobber.create(['/tmp/dir3/file', '/tmp/dir4/file']) + ); + let dirNo = 1; + getCommandOutputSpy.mockImplementation((command: string) => + command.includes('version') ? version : `file_${version}_${dirNo++}` + ); + const dirs = await cacheUtils.getCacheDirectoriesPaths( + supportedPackageManagers.yarn, + cacheDependencyPath + ); + expect(dirs).toEqual([ + `file_${version}_1`, + `file_${version}_2`, + `file_${version}_3`, + `file_${version}_4` + ]); + } + ); + }); }); diff --git a/__tests__/mock/glob-mock.test.ts b/__tests__/mock/glob-mock.test.ts new file mode 100644 index 000000000..db10ced1c --- /dev/null +++ b/__tests__/mock/glob-mock.test.ts @@ -0,0 +1,18 @@ +import {MockGlobber} from './glob-mock'; + +describe('mocked globber tests', () => { + it('globber should return generator', async () => { + const globber = new MockGlobber(['aaa', 'bbb', 'ccc']); + const generator = globber.globGenerator(); + const result: string[] = []; + for await (const itemPath of generator) { + result.push(itemPath); + } + expect(result).toEqual(['aaa', 'bbb', 'ccc']); + }); + it('globber should return glob', async () => { + const globber = new MockGlobber(['aaa', 'bbb', 'ccc']); + const result: string[] = await globber.glob(); + expect(result).toEqual(['aaa', 'bbb', 'ccc']); + }); +}); diff --git a/__tests__/mock/glob-mock.ts b/__tests__/mock/glob-mock.ts new file mode 100644 index 000000000..a2eabf75b --- /dev/null +++ b/__tests__/mock/glob-mock.ts @@ -0,0 +1,29 @@ +import {Globber} from '@actions/glob'; + +export class MockGlobber implements Globber { + private readonly expected: string[]; + constructor(expected: string[]) { + this.expected = expected; + } + getSearchPaths(): string[] { + return this.expected.slice(); + } + + async glob(): Promise { + const result: string[] = []; + for await (const itemPath of this.globGenerator()) { + result.push(itemPath); + } + return result; + } + + async *globGenerator(): AsyncGenerator { + for (const e of this.expected) { + yield e; + } + } + + static async create(expected: string[]): Promise { + return new MockGlobber(expected); + } +} diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index aad770848..6b045c6df 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -6480,6 +6480,1193 @@ class ExecState extends events.EventEmitter { /***/ }), +/***/ 8090: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hashFiles = exports.create = void 0; +const internal_globber_1 = __nccwpck_require__(8298); +const internal_hash_files_1 = __nccwpck_require__(2448); +/** + * Constructs a globber + * + * @param patterns Patterns separated by newlines + * @param options Glob options + */ +function create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + return yield internal_globber_1.DefaultGlobber.create(patterns, options); + }); +} +exports.create = create; +/** + * Computes the sha256 hash of a glob + * + * @param patterns Patterns separated by newlines + * @param options Glob options + */ +function hashFiles(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + let followSymbolicLinks = true; + if (options && typeof options.followSymbolicLinks === 'boolean') { + followSymbolicLinks = options.followSymbolicLinks; + } + const globber = yield create(patterns, { followSymbolicLinks }); + return internal_hash_files_1.hashFiles(globber); + }); +} +exports.hashFiles = hashFiles; +//# sourceMappingURL=glob.js.map + +/***/ }), + +/***/ 1026: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOptions = void 0; +const core = __importStar(__nccwpck_require__(2186)); +/** + * Returns a copy with defaults filled in. + */ +function getOptions(copy) { + const result = { + followSymbolicLinks: true, + implicitDescendants: true, + matchDirectories: true, + omitBrokenSymbolicLinks: true + }; + if (copy) { + if (typeof copy.followSymbolicLinks === 'boolean') { + result.followSymbolicLinks = copy.followSymbolicLinks; + core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); + } + if (typeof copy.implicitDescendants === 'boolean') { + result.implicitDescendants = copy.implicitDescendants; + core.debug(`implicitDescendants '${result.implicitDescendants}'`); + } + if (typeof copy.matchDirectories === 'boolean') { + result.matchDirectories = copy.matchDirectories; + core.debug(`matchDirectories '${result.matchDirectories}'`); + } + if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { + result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; + core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); + } + } + return result; +} +exports.getOptions = getOptions; +//# sourceMappingURL=internal-glob-options-helper.js.map + +/***/ }), + +/***/ 8298: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DefaultGlobber = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const fs = __importStar(__nccwpck_require__(7147)); +const globOptionsHelper = __importStar(__nccwpck_require__(1026)); +const path = __importStar(__nccwpck_require__(1017)); +const patternHelper = __importStar(__nccwpck_require__(9005)); +const internal_match_kind_1 = __nccwpck_require__(1063); +const internal_pattern_1 = __nccwpck_require__(4536); +const internal_search_state_1 = __nccwpck_require__(9117); +const IS_WINDOWS = process.platform === 'win32'; +class DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); + } + getSearchPaths() { + // Return a copy + return this.searchPaths.slice(); + } + glob() { + var e_1, _a; + return __awaiter(this, void 0, void 0, function* () { + const result = []; + try { + for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { + const itemPath = _c.value; + result.push(itemPath); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + return result; + }); + } + globGenerator() { + return __asyncGenerator(this, arguments, function* globGenerator_1() { + // Fill in defaults options + const options = globOptionsHelper.getOptions(this.options); + // Implicit descendants? + const patterns = []; + for (const pattern of this.patterns) { + patterns.push(pattern); + if (options.implicitDescendants && + (pattern.trailingSeparator || + pattern.segments[pattern.segments.length - 1] !== '**')) { + patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); + } + } + // Push the search paths + const stack = []; + for (const searchPath of patternHelper.getSearchPaths(patterns)) { + core.debug(`Search path '${searchPath}'`); + // Exists? + try { + // Intentionally using lstat. Detection for broken symlink + // will be performed later (if following symlinks). + yield __await(fs.promises.lstat(searchPath)); + } + catch (err) { + if (err.code === 'ENOENT') { + continue; + } + throw err; + } + stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); + } + // Search + const traversalChain = []; // used to detect cycles + while (stack.length) { + // Pop + const item = stack.pop(); + // Match? + const match = patternHelper.match(patterns, item.path); + const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); + if (!match && !partialMatch) { + continue; + } + // Stat + const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) + // Broken symlink, or symlink cycle detected, or no longer exists + ); + // Broken symlink, or symlink cycle detected, or no longer exists + if (!stats) { + continue; + } + // Directory + if (stats.isDirectory()) { + // Matched + if (match & internal_match_kind_1.MatchKind.Directory && options.matchDirectories) { + yield yield __await(item.path); + } + // Descend? + else if (!partialMatch) { + continue; + } + // Push the child items in reverse + const childLevel = item.level + 1; + const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); + stack.push(...childItems.reverse()); + } + // File + else if (match & internal_match_kind_1.MatchKind.File) { + yield yield __await(item.path); + } + } + }); + } + /** + * Constructs a DefaultGlobber + */ + static create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + const result = new DefaultGlobber(options); + if (IS_WINDOWS) { + patterns = patterns.replace(/\r\n/g, '\n'); + patterns = patterns.replace(/\r/g, '\n'); + } + const lines = patterns.split('\n').map(x => x.trim()); + for (const line of lines) { + // Empty or comment + if (!line || line.startsWith('#')) { + continue; + } + // Pattern + else { + result.patterns.push(new internal_pattern_1.Pattern(line)); + } + } + result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); + return result; + }); + } + static stat(item, options, traversalChain) { + return __awaiter(this, void 0, void 0, function* () { + // Note: + // `stat` returns info about the target of a symlink (or symlink chain) + // `lstat` returns info about a symlink itself + let stats; + if (options.followSymbolicLinks) { + try { + // Use `stat` (following symlinks) + stats = yield fs.promises.stat(item.path); + } + catch (err) { + if (err.code === 'ENOENT') { + if (options.omitBrokenSymbolicLinks) { + core.debug(`Broken symlink '${item.path}'`); + return undefined; + } + throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + } + throw err; + } + } + else { + // Use `lstat` (not following symlinks) + stats = yield fs.promises.lstat(item.path); + } + // Note, isDirectory() returns false for the lstat of a symlink + if (stats.isDirectory() && options.followSymbolicLinks) { + // Get the realpath + const realPath = yield fs.promises.realpath(item.path); + // Fixup the traversal chain to match the item level + while (traversalChain.length >= item.level) { + traversalChain.pop(); + } + // Test for a cycle + if (traversalChain.some((x) => x === realPath)) { + core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + return undefined; + } + // Update the traversal chain + traversalChain.push(realPath); + } + return stats; + }); + } +} +exports.DefaultGlobber = DefaultGlobber; +//# sourceMappingURL=internal-globber.js.map + +/***/ }), + +/***/ 2448: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hashFiles = void 0; +const crypto = __importStar(__nccwpck_require__(6113)); +const core = __importStar(__nccwpck_require__(2186)); +const fs = __importStar(__nccwpck_require__(7147)); +const stream = __importStar(__nccwpck_require__(2781)); +const util = __importStar(__nccwpck_require__(3837)); +const path = __importStar(__nccwpck_require__(1017)); +function hashFiles(globber) { + var e_1, _a; + var _b; + return __awaiter(this, void 0, void 0, function* () { + let hasMatch = false; + const githubWorkspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); + const result = crypto.createHash('sha256'); + let count = 0; + try { + for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { + const file = _d.value; + core.debug(file); + if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { + core.debug(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); + continue; + } + if (fs.statSync(file).isDirectory()) { + core.debug(`Skip directory '${file}'.`); + continue; + } + const hash = crypto.createHash('sha256'); + const pipeline = util.promisify(stream.pipeline); + yield pipeline(fs.createReadStream(file), hash); + result.write(hash.digest()); + count++; + if (!hasMatch) { + hasMatch = true; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + result.end(); + if (hasMatch) { + core.debug(`Found ${count} files to hash.`); + return result.digest('hex'); + } + else { + core.debug(`No matches found for glob`); + return ''; + } + }); +} +exports.hashFiles = hashFiles; +//# sourceMappingURL=internal-hash-files.js.map + +/***/ }), + +/***/ 1063: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MatchKind = void 0; +/** + * Indicates whether a pattern matches a path + */ +var MatchKind; +(function (MatchKind) { + /** Not matched */ + MatchKind[MatchKind["None"] = 0] = "None"; + /** Matched if the path is a directory */ + MatchKind[MatchKind["Directory"] = 1] = "Directory"; + /** Matched if the path is a regular file */ + MatchKind[MatchKind["File"] = 2] = "File"; + /** Matched */ + MatchKind[MatchKind["All"] = 3] = "All"; +})(MatchKind = exports.MatchKind || (exports.MatchKind = {})); +//# sourceMappingURL=internal-match-kind.js.map + +/***/ }), + +/***/ 1849: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; +const path = __importStar(__nccwpck_require__(1017)); +const assert_1 = __importDefault(__nccwpck_require__(9491)); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. + * + * For example, on Linux/macOS: + * - `/ => /` + * - `/hello => /` + * + * For example, on Windows: + * - `C:\ => C:\` + * - `C:\hello => C:\` + * - `C: => C:` + * - `C:hello => C:` + * - `\ => \` + * - `\hello => \` + * - `\\hello => \\hello` + * - `\\hello\world => \\hello\world` + */ +function dirname(p) { + // Normalize slashes and trim unnecessary trailing slash + p = safeTrimTrailingSeparator(p); + // Windows UNC root, e.g. \\hello or \\hello\world + if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { + return p; + } + // Get dirname + let result = path.dirname(p); + // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ + if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { + result = safeTrimTrailingSeparator(result); + } + return result; +} +exports.dirname = dirname; +/** + * Roots the path if not already rooted. On Windows, relative roots like `\` + * or `C:` are expanded based on the current working directory. + */ +function ensureAbsoluteRoot(root, itemPath) { + assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + // Already rooted + if (hasAbsoluteRoot(itemPath)) { + return itemPath; + } + // Windows + if (IS_WINDOWS) { + // Check for itemPath like C: or C:foo + if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { + let cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + // Drive letter matches cwd? Expand to cwd + if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { + // Drive only, e.g. C: + if (itemPath.length === 2) { + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}`; + } + // Drive + path, e.g. C:foo + else { + if (!cwd.endsWith('\\')) { + cwd += '\\'; + } + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; + } + } + // Different drive + else { + return `${itemPath[0]}:\\${itemPath.substr(2)}`; + } + } + // Check for itemPath like \ or \foo + else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { + const cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + return `${cwd[0]}:\\${itemPath.substr(1)}`; + } + } + assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + // Otherwise ensure root ends with a separator + if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { + // Intentionally empty + } + else { + // Append separator + root += path.sep; + } + return root + itemPath; +} +exports.ensureAbsoluteRoot = ensureAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\\hello\share` and `C:\hello` (and using alternate separator). + */ +function hasAbsoluteRoot(itemPath) { + assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \\hello\share or C:\hello + return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); +} +exports.hasAbsoluteRoot = hasAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). + */ +function hasRoot(itemPath) { + assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \ or \hello or \\hello + // E.g. C: or C:\hello + return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); +} +exports.hasRoot = hasRoot; +/** + * Removes redundant slashes and converts `/` to `\` on Windows + */ +function normalizeSeparators(p) { + p = p || ''; + // Windows + if (IS_WINDOWS) { + // Convert slashes on Windows + p = p.replace(/\//g, '\\'); + // Remove redundant slashes + const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello + return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC + } + // Remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +exports.normalizeSeparators = normalizeSeparators; +/** + * Normalizes the path separators and trims the trailing separator (when safe). + * For example, `/foo/ => /foo` but `/ => /` + */ +function safeTrimTrailingSeparator(p) { + // Short-circuit if empty + if (!p) { + return ''; + } + // Normalize separators + p = normalizeSeparators(p); + // No trailing slash + if (!p.endsWith(path.sep)) { + return p; + } + // Check '/' on Linux/macOS and '\' on Windows + if (p === path.sep) { + return p; + } + // On Windows check if drive root. E.g. C:\ + if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { + return p; + } + // Otherwise trim trailing slash + return p.substr(0, p.length - 1); +} +exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; +//# sourceMappingURL=internal-path-helper.js.map + +/***/ }), + +/***/ 6836: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Path = void 0; +const path = __importStar(__nccwpck_require__(1017)); +const pathHelper = __importStar(__nccwpck_require__(1849)); +const assert_1 = __importDefault(__nccwpck_require__(9491)); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Helper class for parsing paths into segments + */ +class Path { + /** + * Constructs a Path + * @param itemPath Path or array of segments + */ + constructor(itemPath) { + this.segments = []; + // String + if (typeof itemPath === 'string') { + assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // Not rooted + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path.sep); + } + // Rooted + else { + // Add all segments, while not at the root + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + // Add the segment + const basename = path.basename(remaining); + this.segments.unshift(basename); + // Truncate the last segment + remaining = dir; + dir = pathHelper.dirname(remaining); + } + // Remainder is the root + this.segments.unshift(remaining); + } + } + // Array + else { + // Must not be empty + assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + // Each segment + for (let i = 0; i < itemPath.length; i++) { + let segment = itemPath[i]; + // Must not be empty + assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); + // Normalize slashes + segment = pathHelper.normalizeSeparators(itemPath[i]); + // Root segment + if (i === 0 && pathHelper.hasRoot(segment)) { + segment = pathHelper.safeTrimTrailingSeparator(segment); + assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + this.segments.push(segment); + } + // All other segments + else { + // Must not contain slash + assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } + } + } + /** + * Converts the path to it's string representation + */ + toString() { + // First segment + let result = this.segments[0]; + // All others + let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } + else { + result += path.sep; + } + result += this.segments[i]; + } + return result; + } +} +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map + +/***/ }), + +/***/ 9005: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.partialMatch = exports.match = exports.getSearchPaths = void 0; +const pathHelper = __importStar(__nccwpck_require__(1849)); +const internal_match_kind_1 = __nccwpck_require__(1063); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Given an array of patterns, returns an array of paths to search. + * Duplicates and paths under other included paths are filtered out. + */ +function getSearchPaths(patterns) { + // Ignore negate patterns + patterns = patterns.filter(x => !x.negate); + // Create a map of all search paths + const searchPathMap = {}; + for (const pattern of patterns) { + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + searchPathMap[key] = 'candidate'; + } + const result = []; + for (const pattern of patterns) { + // Check if already included + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + if (searchPathMap[key] === 'included') { + continue; + } + // Check for an ancestor search path + let foundAncestor = false; + let tempKey = key; + let parent = pathHelper.dirname(tempKey); + while (parent !== tempKey) { + if (searchPathMap[parent]) { + foundAncestor = true; + break; + } + tempKey = parent; + parent = pathHelper.dirname(tempKey); + } + // Include the search pattern in the result + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = 'included'; + } + } + return result; +} +exports.getSearchPaths = getSearchPaths; +/** + * Matches the patterns against the path + */ +function match(patterns, itemPath) { + let result = internal_match_kind_1.MatchKind.None; + for (const pattern of patterns) { + if (pattern.negate) { + result &= ~pattern.match(itemPath); + } + else { + result |= pattern.match(itemPath); + } + } + return result; +} +exports.match = match; +/** + * Checks whether to descend further into the directory + */ +function partialMatch(patterns, itemPath) { + return patterns.some(x => !x.negate && x.partialMatch(itemPath)); +} +exports.partialMatch = partialMatch; +//# sourceMappingURL=internal-pattern-helper.js.map + +/***/ }), + +/***/ 4536: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Pattern = void 0; +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const pathHelper = __importStar(__nccwpck_require__(1849)); +const assert_1 = __importDefault(__nccwpck_require__(9491)); +const minimatch_1 = __nccwpck_require__(3973); +const internal_match_kind_1 = __nccwpck_require__(1063); +const internal_path_1 = __nccwpck_require__(6836); +const IS_WINDOWS = process.platform === 'win32'; +class Pattern { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { + /** + * Indicates whether matches should be excluded from the result set + */ + this.negate = false; + // Pattern overload + let pattern; + if (typeof patternOrNegate === 'string') { + pattern = patternOrNegate.trim(); + } + // Segments overload + else { + // Convert to pattern + segments = segments || []; + assert_1.default(segments.length, `Parameter 'segments' must not empty`); + const root = Pattern.getLiteral(segments[0]); + assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + pattern = new internal_path_1.Path(segments).toString().trim(); + if (patternOrNegate) { + pattern = `!${pattern}`; + } + } + // Negate + while (pattern.startsWith('!')) { + this.negate = !this.negate; + pattern = pattern.substr(1).trim(); + } + // Normalize slashes and ensures absolute root + pattern = Pattern.fixupPattern(pattern, homedir); + // Segments + this.segments = new internal_path_1.Path(pattern).segments; + // Trailing slash indicates the pattern should only match directories, not regular files + this.trailingSeparator = pathHelper + .normalizeSeparators(pattern) + .endsWith(path.sep); + pattern = pathHelper.safeTrimTrailingSeparator(pattern); + // Search path (literal path prior to the first glob segment) + let foundGlob = false; + const searchSegments = this.segments + .map(x => Pattern.getLiteral(x)) + .filter(x => !foundGlob && !(foundGlob = x === '')); + this.searchPath = new internal_path_1.Path(searchSegments).toString(); + // Root RegExp (required when determining partial match) + this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); + this.isImplicitPattern = isImplicitPattern; + // Create minimatch + const minimatchOptions = { + dot: true, + nobrace: true, + nocase: IS_WINDOWS, + nocomment: true, + noext: true, + nonegate: true + }; + pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; + this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); + } + /** + * Matches the pattern against the specified path + */ + match(itemPath) { + // Last segment is globstar? + if (this.segments[this.segments.length - 1] === '**') { + // Normalize slashes + itemPath = pathHelper.normalizeSeparators(itemPath); + // Append a trailing slash. Otherwise Minimatch will not match the directory immediately + // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. + if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { + // Note, this is safe because the constructor ensures the pattern has an absolute root. + // For example, formats like C: and C:foo on Windows are resolved to an absolute root. + itemPath = `${itemPath}${path.sep}`; + } + } + else { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + } + // Match + if (this.minimatch.match(itemPath)) { + return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; + } + return internal_match_kind_1.MatchKind.None; + } + /** + * Indicates whether the pattern may match descendants of the specified path + */ + partialMatch(itemPath) { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // matchOne does not handle root path correctly + if (pathHelper.dirname(itemPath) === itemPath) { + return this.rootRegExp.test(itemPath); + } + return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); + } + /** + * Escapes glob patterns within a path + */ + static globEscape(s) { + return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS + .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment + .replace(/\?/g, '[?]') // escape '?' + .replace(/\*/g, '[*]'); // escape '*' + } + /** + * Normalizes slashes and ensures absolute root + */ + static fixupPattern(pattern, homedir) { + // Empty + assert_1.default(pattern, 'pattern cannot be empty'); + // Must not contain `.` segment, unless first segment + // Must not contain `..` segment + const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); + assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r + assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + // Normalize slashes + pattern = pathHelper.normalizeSeparators(pattern); + // Replace leading `.` segment + if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { + pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); + } + // Replace leading `~` segment + else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { + homedir = homedir || os.homedir(); + assert_1.default(homedir, 'Unable to determine HOME directory'); + assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + pattern = Pattern.globEscape(homedir) + pattern.substr(1); + } + // Replace relative drive root, e.g. pattern is C: or C:foo + else if (IS_WINDOWS && + (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); + if (pattern.length > 2 && !root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(2); + } + // Replace relative root, e.g. pattern is \ or \foo + else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); + if (!root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(1); + } + // Otherwise ensure absolute root + else { + pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); + } + return pathHelper.normalizeSeparators(pattern); + } + /** + * Attempts to unescape a pattern segment to create a literal path segment. + * Otherwise returns empty string. + */ + static getLiteral(segment) { + let literal = ''; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + // Escape + if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { + literal += segment[++i]; + continue; + } + // Wildcard + else if (c === '*' || c === '?') { + return ''; + } + // Character set + else if (c === '[' && i + 1 < segment.length) { + let set = ''; + let closed = -1; + for (let i2 = i + 1; i2 < segment.length; i2++) { + const c2 = segment[i2]; + // Escape + if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { + set += segment[++i2]; + continue; + } + // Closed + else if (c2 === ']') { + closed = i2; + break; + } + // Otherwise + else { + set += c2; + } + } + // Closed? + if (closed >= 0) { + // Cannot convert + if (set.length > 1) { + return ''; + } + // Convert to literal + if (set) { + literal += set; + i = closed; + continue; + } + } + // Otherwise fall thru + } + // Append + literal += c; + } + return literal; + } + /** + * Escapes regexp special characters + * https://javascript.info/regexp-escaping + */ + static regExpEscape(s) { + return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); + } +} +exports.Pattern = Pattern; +//# sourceMappingURL=internal-pattern.js.map + +/***/ }), + +/***/ 9117: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SearchState = void 0; +class SearchState { + constructor(path, level) { + this.path = path; + this.level = level; + } +} +exports.SearchState = SearchState; +//# sourceMappingURL=internal-search-state.js.map + +/***/ }), + /***/ 1962: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -59155,14 +60342,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.run = void 0; const core = __importStar(__nccwpck_require__(2186)); const cache = __importStar(__nccwpck_require__(7799)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); const constants_1 = __nccwpck_require__(9042); const cache_utils_1 = __nccwpck_require__(1678); // Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in @@ -59192,15 +60375,18 @@ const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, func core.debug(`Caching for '${packageManager}' is not supported`); return; } - const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); - if (!fs_1.default.existsSync(cachePath)) { - throw new Error(`Cache folder path is retrieved for ${packageManager} but doesn't exist on disk: ${cachePath}`); + // TODO: core.getInput has a bug - it can return undefined despite its definition + // export declare function getInput(name: string, options?: InputOptions): string; + const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; + const cachePaths = yield cache_utils_1.getCacheDirectoriesPaths(packageManagerInfo, cacheDependencyPath); + if (cachePaths.length === 0) { + throw new Error(`Cache folder paths are not retrieved for ${packageManager} with cache-dependency-path = ${cacheDependencyPath}`); } if (primaryKey === state) { core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`); return; } - const cacheId = yield cache.saveCache([cachePath], primaryKey); + const cacheId = yield cache.saveCache(cachePaths, primaryKey); if (cacheId == -1) { return; } @@ -59248,32 +60434,47 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerVersion = exports.getPackageManagerCommandOutput = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoriesPaths = exports.expandCacheDependencyPath = exports.getPackageManagerInfo = exports.getCommandOutputGuarded = exports.getCommandOutput = exports.supportedPackageManagers = exports.yarn2GetCacheFolderCommand = exports.yarn1GetCacheFolderCommand = exports.pnpmGetCacheFolderCommand = exports.npmGetCacheFolderCommand = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); +const glob = __importStar(__nccwpck_require__(8090)); const path_1 = __importDefault(__nccwpck_require__(1017)); const fs_1 = __importDefault(__nccwpck_require__(7147)); +// for testing purposes +exports.npmGetCacheFolderCommand = 'npm config get cache'; +exports.pnpmGetCacheFolderCommand = 'pnpm store path --silent'; +exports.yarn1GetCacheFolderCommand = 'yarn cache dir'; +exports.yarn2GetCacheFolderCommand = 'yarn config get cacheFolder'; exports.supportedPackageManagers = { npm: { + name: 'npm', lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], - getCacheFolderCommand: 'npm config get cache' + getCacheFolderPath: () => exports.getCommandOutputGuarded(exports.npmGetCacheFolderCommand, 'Could not get npm cache folder path') }, pnpm: { + name: 'pnpm', lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path --silent' + getCacheFolderPath: () => exports.getCommandOutputGuarded(exports.pnpmGetCacheFolderCommand, 'Could not get pnpm cache folder path') }, - yarn1: { + yarn: { + name: 'yarn', lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn cache dir' - }, - yarn2: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn config get cacheFolder' + getCacheFolderPath: (projectDir) => __awaiter(void 0, void 0, void 0, function* () { + const yarnVersion = yield exports.getCommandOutputGuarded(`yarn --version`, 'Could not retrieve version of yarn', projectDir); + core.debug(`Consumed yarn version is ${yarnVersion}`); + const stdOut = yarnVersion.startsWith('1.') + ? yield exports.getCommandOutput(exports.yarn1GetCacheFolderCommand, projectDir) + : yield exports.getCommandOutput(exports.yarn2GetCacheFolderCommand, projectDir); + if (!stdOut) { + throw new Error(`Could not get yarn cache folder path for ${projectDir}`); + } + return stdOut; + }) } }; const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, function* () { - let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, Object.assign({ ignoreReturnCode: true }, (cwd !== null && { cwd }))); + let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, Object.assign({ ignoreReturnCode: true }, (cwd && { cwd }))); if (exitCode) { stderr = !stderr.trim() ? `The '${toolCommand}' command failed with exit code: ${exitCode}` @@ -59283,32 +60484,14 @@ const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, return stdout.trim(); }); exports.getCommandOutput = getCommandOutput; -const getPackageManagerWorkingDir = () => { - const cache = core.getInput('cache'); - if (cache !== 'yarn') { - return null; - } - const cacheDependencyPath = core.getInput('cache-dependency-path'); - if (!cacheDependencyPath) { - return null; - } - const wd = path_1.default.dirname(cacheDependencyPath); - if (fs_1.default.existsSync(wd) && fs_1.default.lstatSync(wd).isDirectory()) { - return wd; - } - return null; -}; -exports.getPackageManagerWorkingDir = getPackageManagerWorkingDir; -const getPackageManagerCommandOutput = (command) => exports.getCommandOutput(command, exports.getPackageManagerWorkingDir()); -exports.getPackageManagerCommandOutput = getPackageManagerCommandOutput; -const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getPackageManagerCommandOutput(`${packageManager} ${command}`); +const getCommandOutputGuarded = (toolCommand, error, cwd) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = exports.getCommandOutput(toolCommand, cwd); if (!stdOut) { - throw new Error(`Could not retrieve version of ${packageManager}`); + throw new Error(error); } return stdOut; }); -exports.getPackageManagerVersion = getPackageManagerVersion; +exports.getCommandOutputGuarded = getCommandOutputGuarded; const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { if (packageManager === 'npm') { return exports.supportedPackageManagers.npm; @@ -59317,29 +60500,56 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void return exports.supportedPackageManagers.pnpm; } else if (packageManager === 'yarn') { - const yarnVersion = yield exports.getPackageManagerVersion('yarn', '--version'); - core.debug(`Consumed yarn version is ${yarnVersion}`); - if (yarnVersion.startsWith('1.')) { - return exports.supportedPackageManagers.yarn1; - } - else { - return exports.supportedPackageManagers.yarn2; - } + return exports.supportedPackageManagers.yarn; } else { return null; } }); exports.getPackageManagerInfo = getPackageManagerInfo; -const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getPackageManagerCommandOutput(packageManagerInfo.getCacheFolderCommand); - if (!stdOut) { - throw new Error(`Could not get cache folder path for ${packageManager}`); - } - core.debug(`${packageManager} path is ${stdOut}`); - return stdOut.trim(); +const globPatternToArray = (pattern) => __awaiter(void 0, void 0, void 0, function* () { + const globber = yield glob.create(pattern); + return globber.glob(); +}); +const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const multilinePaths = cacheDependencyPath + .split(/\r?\n/) + .map(path => path.trim()) + .filter(path => Boolean(path)); + const expandedPathsPromises = multilinePaths.map(path => path.includes('*') ? globPatternToArray(path) : Promise.resolve([path])); + const expandedPaths = yield Promise.all(expandedPathsPromises); + return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); +}); +exports.expandCacheDependencyPath = expandCacheDependencyPath; +const cacheDependencyPathToCacheFolderPath = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const cacheDependencyPathDirectory = path_1.default.dirname(cacheDependencyPath); + const cacheFolderPath = fs_1.default.existsSync(cacheDependencyPathDirectory) && + fs_1.default.lstatSync(cacheDependencyPathDirectory).isDirectory() + ? yield packageManagerInfo.getCacheFolderPath(cacheDependencyPathDirectory) + : yield packageManagerInfo.getCacheFolderPath(); + core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath} (derived from cache-dependency-path: "${cacheDependencyPath}")`); + return cacheFolderPath; +}); +const cacheDependenciesPathsToCacheFoldersPaths = (packageManagerInfo, cacheDependenciesPaths) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFoldersPaths = yield Promise.all(cacheDependenciesPaths.map(cacheDependencyPath => cacheDependencyPathToCacheFolderPath(packageManagerInfo, cacheDependencyPath))); + return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); +}); +const cacheDependencyPathToCacheFoldersPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const cacheDependenciesPaths = yield exports.expandCacheDependencyPath(cacheDependencyPath); + return cacheDependenciesPathsToCacheFoldersPaths(packageManagerInfo, cacheDependenciesPaths); +}); +const cacheFoldersPathsForRoot = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(); + core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath}`); + return [cacheFolderPath]; +}); +const getCacheDirectoriesPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + // TODO: multiple directories limited to yarn so far + return packageManagerInfo === exports.supportedPackageManagers.yarn + ? cacheDependencyPathToCacheFoldersPaths(packageManagerInfo, cacheDependencyPath) + : cacheFoldersPathsForRoot(packageManagerInfo); }); -exports.getCacheDirectoryPath = getCacheDirectoryPath; +exports.getCacheDirectoriesPaths = getCacheDirectoriesPaths; function isGhes() { const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; diff --git a/dist/setup/index.js b/dist/setup/index.js index eae17a848..7230bd041 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71144,7 +71144,7 @@ const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, throw new Error(`Caching for '${packageManager}' is not supported`); } const platform = process.env.RUNNER_OS; - const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); + const cachePaths = yield cache_utils_1.getCacheDirectoriesPaths(packageManagerInfo, cacheDependencyPath); const lockFilePath = cacheDependencyPath ? cacheDependencyPath : findLockFile(packageManagerInfo); @@ -71155,7 +71155,7 @@ const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, const primaryKey = `node-cache-${platform}-${packageManager}-v2-${fileHash}`; core.debug(`primary key is ${primaryKey}`); core.saveState(constants_1.State.CachePrimaryKey, primaryKey); - const cacheKey = yield cache.restoreCache([cachePath], primaryKey); + const cacheKey = yield cache.restoreCache(cachePaths, primaryKey); core.setOutput('cache-hit', Boolean(cacheKey)); if (!cacheKey) { core.info(`${packageManager} cache is not found`); @@ -71216,32 +71216,47 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoryPath = exports.getPackageManagerInfo = exports.getPackageManagerVersion = exports.getPackageManagerCommandOutput = exports.getPackageManagerWorkingDir = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoriesPaths = exports.expandCacheDependencyPath = exports.getPackageManagerInfo = exports.getCommandOutputGuarded = exports.getCommandOutput = exports.supportedPackageManagers = exports.yarn2GetCacheFolderCommand = exports.yarn1GetCacheFolderCommand = exports.pnpmGetCacheFolderCommand = exports.npmGetCacheFolderCommand = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); +const glob = __importStar(__nccwpck_require__(8090)); const path_1 = __importDefault(__nccwpck_require__(1017)); const fs_1 = __importDefault(__nccwpck_require__(7147)); +// for testing purposes +exports.npmGetCacheFolderCommand = 'npm config get cache'; +exports.pnpmGetCacheFolderCommand = 'pnpm store path --silent'; +exports.yarn1GetCacheFolderCommand = 'yarn cache dir'; +exports.yarn2GetCacheFolderCommand = 'yarn config get cacheFolder'; exports.supportedPackageManagers = { npm: { + name: 'npm', lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], - getCacheFolderCommand: 'npm config get cache' + getCacheFolderPath: () => exports.getCommandOutputGuarded(exports.npmGetCacheFolderCommand, 'Could not get npm cache folder path') }, pnpm: { + name: 'pnpm', lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path --silent' - }, - yarn1: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn cache dir' + getCacheFolderPath: () => exports.getCommandOutputGuarded(exports.pnpmGetCacheFolderCommand, 'Could not get pnpm cache folder path') }, - yarn2: { + yarn: { + name: 'yarn', lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn config get cacheFolder' + getCacheFolderPath: (projectDir) => __awaiter(void 0, void 0, void 0, function* () { + const yarnVersion = yield exports.getCommandOutputGuarded(`yarn --version`, 'Could not retrieve version of yarn', projectDir); + core.debug(`Consumed yarn version is ${yarnVersion}`); + const stdOut = yarnVersion.startsWith('1.') + ? yield exports.getCommandOutput(exports.yarn1GetCacheFolderCommand, projectDir) + : yield exports.getCommandOutput(exports.yarn2GetCacheFolderCommand, projectDir); + if (!stdOut) { + throw new Error(`Could not get yarn cache folder path for ${projectDir}`); + } + return stdOut; + }) } }; const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, function* () { - let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, Object.assign({ ignoreReturnCode: true }, (cwd !== null && { cwd }))); + let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, Object.assign({ ignoreReturnCode: true }, (cwd && { cwd }))); if (exitCode) { stderr = !stderr.trim() ? `The '${toolCommand}' command failed with exit code: ${exitCode}` @@ -71251,32 +71266,14 @@ const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, return stdout.trim(); }); exports.getCommandOutput = getCommandOutput; -const getPackageManagerWorkingDir = () => { - const cache = core.getInput('cache'); - if (cache !== 'yarn') { - return null; - } - const cacheDependencyPath = core.getInput('cache-dependency-path'); - if (!cacheDependencyPath) { - return null; - } - const wd = path_1.default.dirname(cacheDependencyPath); - if (fs_1.default.existsSync(wd) && fs_1.default.lstatSync(wd).isDirectory()) { - return wd; - } - return null; -}; -exports.getPackageManagerWorkingDir = getPackageManagerWorkingDir; -const getPackageManagerCommandOutput = (command) => exports.getCommandOutput(command, exports.getPackageManagerWorkingDir()); -exports.getPackageManagerCommandOutput = getPackageManagerCommandOutput; -const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getPackageManagerCommandOutput(`${packageManager} ${command}`); +const getCommandOutputGuarded = (toolCommand, error, cwd) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = exports.getCommandOutput(toolCommand, cwd); if (!stdOut) { - throw new Error(`Could not retrieve version of ${packageManager}`); + throw new Error(error); } return stdOut; }); -exports.getPackageManagerVersion = getPackageManagerVersion; +exports.getCommandOutputGuarded = getCommandOutputGuarded; const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { if (packageManager === 'npm') { return exports.supportedPackageManagers.npm; @@ -71285,29 +71282,56 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void return exports.supportedPackageManagers.pnpm; } else if (packageManager === 'yarn') { - const yarnVersion = yield exports.getPackageManagerVersion('yarn', '--version'); - core.debug(`Consumed yarn version is ${yarnVersion}`); - if (yarnVersion.startsWith('1.')) { - return exports.supportedPackageManagers.yarn1; - } - else { - return exports.supportedPackageManagers.yarn2; - } + return exports.supportedPackageManagers.yarn; } else { return null; } }); exports.getPackageManagerInfo = getPackageManagerInfo; -const getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getPackageManagerCommandOutput(packageManagerInfo.getCacheFolderCommand); - if (!stdOut) { - throw new Error(`Could not get cache folder path for ${packageManager}`); - } - core.debug(`${packageManager} path is ${stdOut}`); - return stdOut.trim(); +const globPatternToArray = (pattern) => __awaiter(void 0, void 0, void 0, function* () { + const globber = yield glob.create(pattern); + return globber.glob(); +}); +const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const multilinePaths = cacheDependencyPath + .split(/\r?\n/) + .map(path => path.trim()) + .filter(path => Boolean(path)); + const expandedPathsPromises = multilinePaths.map(path => path.includes('*') ? globPatternToArray(path) : Promise.resolve([path])); + const expandedPaths = yield Promise.all(expandedPathsPromises); + return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); +}); +exports.expandCacheDependencyPath = expandCacheDependencyPath; +const cacheDependencyPathToCacheFolderPath = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const cacheDependencyPathDirectory = path_1.default.dirname(cacheDependencyPath); + const cacheFolderPath = fs_1.default.existsSync(cacheDependencyPathDirectory) && + fs_1.default.lstatSync(cacheDependencyPathDirectory).isDirectory() + ? yield packageManagerInfo.getCacheFolderPath(cacheDependencyPathDirectory) + : yield packageManagerInfo.getCacheFolderPath(); + core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath} (derived from cache-dependency-path: "${cacheDependencyPath}")`); + return cacheFolderPath; +}); +const cacheDependenciesPathsToCacheFoldersPaths = (packageManagerInfo, cacheDependenciesPaths) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFoldersPaths = yield Promise.all(cacheDependenciesPaths.map(cacheDependencyPath => cacheDependencyPathToCacheFolderPath(packageManagerInfo, cacheDependencyPath))); + return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); +}); +const cacheDependencyPathToCacheFoldersPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const cacheDependenciesPaths = yield exports.expandCacheDependencyPath(cacheDependencyPath); + return cacheDependenciesPathsToCacheFoldersPaths(packageManagerInfo, cacheDependenciesPaths); +}); +const cacheFoldersPathsForRoot = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(); + core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath}`); + return [cacheFolderPath]; +}); +const getCacheDirectoriesPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + // TODO: multiple directories limited to yarn so far + return packageManagerInfo === exports.supportedPackageManagers.yarn + ? cacheDependencyPathToCacheFoldersPaths(packageManagerInfo, cacheDependencyPath) + : cacheFoldersPathsForRoot(packageManagerInfo); }); -exports.getCacheDirectoryPath = getCacheDirectoryPath; +exports.getCacheDirectoriesPaths = getCacheDirectoriesPaths; function isGhes() { const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; diff --git a/src/cache-restore.ts b/src/cache-restore.ts index 0341c109f..801d525c2 100644 --- a/src/cache-restore.ts +++ b/src/cache-restore.ts @@ -6,14 +6,14 @@ import fs from 'fs'; import {State} from './constants'; import { - getCacheDirectoryPath, + getCacheDirectoriesPaths, getPackageManagerInfo, PackageManagerInfo } from './cache-utils'; export const restoreCache = async ( packageManager: string, - cacheDependencyPath?: string + cacheDependencyPath: string ) => { const packageManagerInfo = await getPackageManagerInfo(packageManager); if (!packageManagerInfo) { @@ -21,9 +21,9 @@ export const restoreCache = async ( } const platform = process.env.RUNNER_OS; - const cachePath = await getCacheDirectoryPath( + const cachePaths = await getCacheDirectoriesPaths( packageManagerInfo, - packageManager + cacheDependencyPath ); const lockFilePath = cacheDependencyPath ? cacheDependencyPath @@ -41,7 +41,7 @@ export const restoreCache = async ( core.saveState(State.CachePrimaryKey, primaryKey); - const cacheKey = await cache.restoreCache([cachePath], primaryKey); + const cacheKey = await cache.restoreCache(cachePaths, primaryKey); core.setOutput('cache-hit', Boolean(cacheKey)); if (!cacheKey) { diff --git a/src/cache-save.ts b/src/cache-save.ts index 24565a8e6..660ec37c7 100644 --- a/src/cache-save.ts +++ b/src/cache-save.ts @@ -2,7 +2,7 @@ import * as core from '@actions/core'; import * as cache from '@actions/cache'; import fs from 'fs'; import {State} from './constants'; -import {getCacheDirectoryPath, getPackageManagerInfo} from './cache-utils'; +import {getCacheDirectoriesPaths, getPackageManagerInfo} from './cache-utils'; // Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in // @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to @@ -31,14 +31,17 @@ const cachePackages = async (packageManager: string) => { return; } - const cachePath = await getCacheDirectoryPath( + // TODO: core.getInput has a bug - it can return undefined despite its definition + // export declare function getInput(name: string, options?: InputOptions): string; + const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; + const cachePaths = await getCacheDirectoriesPaths( packageManagerInfo, - packageManager + cacheDependencyPath ); - if (!fs.existsSync(cachePath)) { + if (cachePaths.length === 0) { throw new Error( - `Cache folder path is retrieved for ${packageManager} but doesn't exist on disk: ${cachePath}` + `Cache folder paths are not retrieved for ${packageManager} with cache-dependency-path = ${cacheDependencyPath}` ); } @@ -49,7 +52,7 @@ const cachePackages = async (packageManager: string) => { return; } - const cacheId = await cache.saveCache([cachePath], primaryKey); + const cacheId = await cache.saveCache(cachePaths, primaryKey); if (cacheId == -1) { return; } diff --git a/src/cache-utils.ts b/src/cache-utils.ts index ebd5144b1..9c7f28272 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -1,45 +1,80 @@ import * as core from '@actions/core'; import * as exec from '@actions/exec'; import * as cache from '@actions/cache'; +import * as glob from '@actions/glob'; import path from 'path'; import fs from 'fs'; -type SupportedPackageManagers = { - [prop: string]: PackageManagerInfo; -}; - export interface PackageManagerInfo { + name: string; lockFilePatterns: Array; - getCacheFolderCommand: string; + getCacheFolderPath: (projectDir?: string) => Promise; +} + +interface SupportedPackageManagers { + npm: PackageManagerInfo; + pnpm: PackageManagerInfo; + yarn: PackageManagerInfo; } +// for testing purposes +export const npmGetCacheFolderCommand = 'npm config get cache'; +export const pnpmGetCacheFolderCommand = 'pnpm store path --silent'; +export const yarn1GetCacheFolderCommand = 'yarn cache dir'; +export const yarn2GetCacheFolderCommand = 'yarn config get cacheFolder'; export const supportedPackageManagers: SupportedPackageManagers = { npm: { + name: 'npm', lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], - getCacheFolderCommand: 'npm config get cache' + getCacheFolderPath: () => + getCommandOutputGuarded( + npmGetCacheFolderCommand, + 'Could not get npm cache folder path' + ) }, pnpm: { + name: 'pnpm', lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path --silent' - }, - yarn1: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn cache dir' + getCacheFolderPath: () => + getCommandOutputGuarded( + pnpmGetCacheFolderCommand, + 'Could not get pnpm cache folder path' + ) }, - yarn2: { + yarn: { + name: 'yarn', lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn config get cacheFolder' + getCacheFolderPath: async projectDir => { + const yarnVersion = await getCommandOutputGuarded( + `yarn --version`, + 'Could not retrieve version of yarn', + projectDir + ); + + core.debug(`Consumed yarn version is ${yarnVersion}`); + + const stdOut = yarnVersion.startsWith('1.') + ? await getCommandOutput(yarn1GetCacheFolderCommand, projectDir) + : await getCommandOutput(yarn2GetCacheFolderCommand, projectDir); + + if (!stdOut) { + throw new Error( + `Could not get yarn cache folder path for ${projectDir}` + ); + } + return stdOut; + } } }; export const getCommandOutput = async ( toolCommand: string, - cwd: string | null -) => { + cwd?: string +): Promise => { let {stdout, stderr, exitCode} = await exec.getExecOutput( toolCommand, undefined, - {ignoreReturnCode: true, ...(cwd !== null && {cwd})} + {ignoreReturnCode: true, ...(cwd && {cwd})} ); if (exitCode) { @@ -52,41 +87,15 @@ export const getCommandOutput = async ( return stdout.trim(); }; -export const getPackageManagerWorkingDir = (): string | null => { - const cache = core.getInput('cache'); - if (cache !== 'yarn') { - return null; - } - - const cacheDependencyPath = core.getInput('cache-dependency-path'); - if (!cacheDependencyPath) { - return null; - } - - const wd = path.dirname(cacheDependencyPath); - - if (fs.existsSync(wd) && fs.lstatSync(wd).isDirectory()) { - return wd; - } - - return null; -}; - -export const getPackageManagerCommandOutput = (command: string) => - getCommandOutput(command, getPackageManagerWorkingDir()); - -export const getPackageManagerVersion = async ( - packageManager: string, - command: string -) => { - const stdOut = await getPackageManagerCommandOutput( - `${packageManager} ${command}` - ); - +export const getCommandOutputGuarded = async ( + toolCommand: string, + error: string, + cwd?: string +): Promise => { + const stdOut = getCommandOutput(toolCommand, cwd); if (!stdOut) { - throw new Error(`Could not retrieve version of ${packageManager}`); + throw new Error(error); } - return stdOut; }; @@ -96,37 +105,100 @@ export const getPackageManagerInfo = async (packageManager: string) => { } else if (packageManager === 'pnpm') { return supportedPackageManagers.pnpm; } else if (packageManager === 'yarn') { - const yarnVersion = await getPackageManagerVersion('yarn', '--version'); - - core.debug(`Consumed yarn version is ${yarnVersion}`); - - if (yarnVersion.startsWith('1.')) { - return supportedPackageManagers.yarn1; - } else { - return supportedPackageManagers.yarn2; - } + return supportedPackageManagers.yarn; } else { return null; } }; -export const getCacheDirectoryPath = async ( +const globPatternToArray = async (pattern: string): Promise => { + const globber = await glob.create(pattern); + return globber.glob(); +}; + +export const expandCacheDependencyPath = async ( + cacheDependencyPath: string +): Promise => { + const multilinePaths = cacheDependencyPath + .split(/\r?\n/) + .map(path => path.trim()) + .filter(path => Boolean(path)); + const expandedPathsPromises: Promise[] = multilinePaths.map(path => + path.includes('*') ? globPatternToArray(path) : Promise.resolve([path]) + ); + const expandedPaths: string[][] = await Promise.all(expandedPathsPromises); + return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); +}; + +const cacheDependencyPathToCacheFolderPath = async ( packageManagerInfo: PackageManagerInfo, - packageManager: string -) => { - const stdOut = await getPackageManagerCommandOutput( - packageManagerInfo.getCacheFolderCommand + cacheDependencyPath: string +): Promise => { + const cacheDependencyPathDirectory = path.dirname(cacheDependencyPath); + const cacheFolderPath = + fs.existsSync(cacheDependencyPathDirectory) && + fs.lstatSync(cacheDependencyPathDirectory).isDirectory() + ? await packageManagerInfo.getCacheFolderPath( + cacheDependencyPathDirectory + ) + : await packageManagerInfo.getCacheFolderPath(); + + core.debug( + `${packageManagerInfo.name} path is ${cacheFolderPath} (derived from cache-dependency-path: "${cacheDependencyPath}")` ); - if (!stdOut) { - throw new Error(`Could not get cache folder path for ${packageManager}`); - } + return cacheFolderPath; +}; +const cacheDependenciesPathsToCacheFoldersPaths = async ( + packageManagerInfo: PackageManagerInfo, + cacheDependenciesPaths: string[] +): Promise => { + const cacheFoldersPaths = await Promise.all( + cacheDependenciesPaths.map(cacheDependencyPath => + cacheDependencyPathToCacheFolderPath( + packageManagerInfo, + cacheDependencyPath + ) + ) + ); + return cacheFoldersPaths.filter( + (cachePath, i, result) => result.indexOf(cachePath) === i + ); +}; - core.debug(`${packageManager} path is ${stdOut}`); +const cacheDependencyPathToCacheFoldersPaths = async ( + packageManagerInfo: PackageManagerInfo, + cacheDependencyPath: string +): Promise => { + const cacheDependenciesPaths = await expandCacheDependencyPath( + cacheDependencyPath + ); + return cacheDependenciesPathsToCacheFoldersPaths( + packageManagerInfo, + cacheDependenciesPaths + ); +}; - return stdOut.trim(); +const cacheFoldersPathsForRoot = async ( + packageManagerInfo: PackageManagerInfo +): Promise => { + const cacheFolderPath = await packageManagerInfo.getCacheFolderPath(); + core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath}`); + return [cacheFolderPath]; }; +export const getCacheDirectoriesPaths = async ( + packageManagerInfo: PackageManagerInfo, + cacheDependencyPath: string +): Promise => + // TODO: multiple directories limited to yarn so far + packageManagerInfo === supportedPackageManagers.yarn + ? cacheDependencyPathToCacheFoldersPaths( + packageManagerInfo, + cacheDependencyPath + ) + : cacheFoldersPathsForRoot(packageManagerInfo); + export function isGhes(): boolean { const ghUrl = new URL( process.env['GITHUB_SERVER_URL'] || 'https://github.com' From 5de08eab2b866c48fc19fb345ebac827900aa21f Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Fri, 19 May 2023 19:57:43 +0200 Subject: [PATCH 12/21] refactor, introduce `cacheDependencyPathToProjectsDirectories` it is necessary for the next PR related yarn optimization --- __tests__/cache-save.test.ts | 60 +++++++++++++---- __tests__/cache-utils.test.ts | 41 +++++++++--- dist/cache-save/index.js | 76 ++++++++++++++++----- dist/setup/index.js | 76 ++++++++++++++++----- src/cache-utils.ts | 121 ++++++++++++++++++++++++++-------- 5 files changed, 293 insertions(+), 81 deletions(-) diff --git a/__tests__/cache-save.test.ts b/__tests__/cache-save.test.ts index 0651138e3..4fc997920 100644 --- a/__tests__/cache-save.test.ts +++ b/__tests__/cache-save.test.ts @@ -118,9 +118,14 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); expect(debugSpy).toHaveBeenCalledWith( - 'yarn path is /some/random/path/yarn1 (derived from cache-dependency-path: "")' + 'Project directory "." derived from cache-dependency-path: ""' + ); + expect(debugSpy).toHaveBeenCalledWith( + 'Consumed yarn version is 1.2.3 (working dir: ".")' + ); + expect(debugSpy).toHaveBeenCalledWith( + 'yarn\'s cache folder "/some/random/path/yarn1" configured for the directory "."' ); - expect(debugSpy).toHaveBeenCalledWith('Consumed yarn version is 1.2.3'); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); @@ -140,9 +145,14 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); expect(debugSpy).toHaveBeenCalledWith( - 'yarn path is /some/random/path/yarn2 (derived from cache-dependency-path: "")' + 'Project directory "." derived from cache-dependency-path: ""' + ); + expect(debugSpy).toHaveBeenCalledWith( + 'Consumed yarn version is 2.2.3 (working dir: ".")' + ); + expect(debugSpy).toHaveBeenCalledWith( + 'yarn\'s cache folder "/some/random/path/yarn2" configured for the directory "."' ); - expect(debugSpy).toHaveBeenCalledWith('Consumed yarn version is 2.2.3'); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); @@ -159,7 +169,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith(`npm path is ${commonPath}/npm`); + expect(debugSpy).toHaveBeenCalledWith( + `npm's cache folder "${commonPath}/npm" configured for the root directory` + ); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` ); @@ -176,7 +188,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith(`pnpm path is ${commonPath}/pnpm`); + expect(debugSpy).toHaveBeenCalledWith( + `pnpm's cache folder "${commonPath}/pnpm" configured for the root directory` + ); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${pnpmFileHash}, not saving cache.` ); @@ -204,9 +218,14 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); expect(debugSpy).toHaveBeenCalledWith( - 'yarn path is /some/random/path/yarn1 (derived from cache-dependency-path: "")' + 'Project directory "." derived from cache-dependency-path: ""' + ); + expect(debugSpy).toHaveBeenCalledWith( + 'Consumed yarn version is 1.2.3 (working dir: ".")' + ); + expect(debugSpy).toHaveBeenCalledWith( + 'yarn\'s cache folder "/some/random/path/yarn1" configured for the directory "."' ); - expect(debugSpy).toHaveBeenCalledWith('Consumed yarn version is 1.2.3'); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); @@ -236,9 +255,14 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); expect(debugSpy).toHaveBeenCalledWith( - 'yarn path is /some/random/path/yarn2 (derived from cache-dependency-path: "")' + 'Project directory "." derived from cache-dependency-path: ""' + ); + expect(debugSpy).toHaveBeenCalledWith( + 'Consumed yarn version is 2.2.3 (working dir: ".")' + ); + expect(debugSpy).toHaveBeenCalledWith( + 'yarn\'s cache folder "/some/random/path/yarn2" configured for the directory "."' ); - expect(debugSpy).toHaveBeenCalledWith('Consumed yarn version is 2.2.3'); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); @@ -265,7 +289,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith(`npm path is ${commonPath}/npm`); + expect(debugSpy).toHaveBeenCalledWith( + `npm's cache folder "${commonPath}/npm" configured for the root directory` + ); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` ); @@ -292,7 +318,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith(`pnpm path is ${commonPath}/pnpm`); + expect(debugSpy).toHaveBeenCalledWith( + `pnpm's cache folder "${commonPath}/pnpm" configured for the root directory` + ); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${pnpmFileHash}, not saving cache.` ); @@ -322,7 +350,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith(`npm path is ${commonPath}/npm`); + expect(debugSpy).toHaveBeenCalledWith( + `npm's cache folder "${commonPath}/npm" configured for the root directory` + ); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` ); @@ -352,7 +382,9 @@ describe('run', () => { expect(getInputSpy).toHaveBeenCalled(); expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith(`npm path is ${commonPath}/npm`); + expect(debugSpy).toHaveBeenCalledWith( + `npm's cache folder "${commonPath}/npm" configured for the root directory` + ); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` ); diff --git a/__tests__/cache-utils.test.ts b/__tests__/cache-utils.test.ts index 80e4a0844..789d3ba61 100644 --- a/__tests__/cache-utils.test.ts +++ b/__tests__/cache-utils.test.ts @@ -7,7 +7,8 @@ import { isCacheFeatureAvailable, supportedPackageManagers, getCommandOutput, - expandCacheDependencyPath + expandCacheDependencyPath, + expandedPatternsMemoized } from '../src/cache-utils'; import fs from 'fs'; import * as cacheUtils from '../src/cache-utils'; @@ -104,6 +105,10 @@ describe('cache-utils', () => { (pattern: string): Promise => MockGlobber.create(['/foo', '/bar']) ); + + Object.keys(expandedPatternsMemoized).forEach( + key => delete expandedPatternsMemoized[key] + ); }); afterEach(() => { @@ -194,13 +199,36 @@ two [supportedPackageManagers.yarn, '/dir/file.lock'], [supportedPackageManagers.yarn, '/**/file.lock'] ])( - 'getCacheDirectoriesPaths should return empty array of folder in case of error', + 'getCacheDirectoriesPaths should throw for getCommandOutput returning empty', async (packageManagerInfo, cacheDependency) => { getCommandOutputSpy.mockImplementation((command: string) => // return empty string to indicate getCacheFolderPath failed // --version still works command.includes('version') ? '1.' : '' ); + + await expect( + cacheUtils.getCacheDirectoriesPaths( + packageManagerInfo, + cacheDependency + ) + ).rejects.toThrow(); //'Could not get cache folder path for /dir'); + } + ); + + it.each([ + [supportedPackageManagers.npm, ''], + [supportedPackageManagers.npm, '/dir/file.lock'], + [supportedPackageManagers.npm, '/**/file.lock'], + [supportedPackageManagers.pnpm, ''], + [supportedPackageManagers.pnpm, '/dir/file.lock'], + [supportedPackageManagers.pnpm, '/**/file.lock'], + [supportedPackageManagers.yarn, ''], + [supportedPackageManagers.yarn, '/dir/file.lock'], + [supportedPackageManagers.yarn, '/**/file.lock'] + ])( + 'getCacheDirectoriesPaths should throw in case of having not directories', + async (packageManagerInfo, cacheDependency) => { lstatSpy.mockImplementation(arg => ({ isDirectory: () => false })); @@ -248,9 +276,8 @@ two } ); - // TODO: by design - glob is not expected to return duplicates so 3 patterns do not collapse to 2 it.each(['1.1.1', '2.2.2'])( - 'getCacheDirectoriesPaths yarn v%s should return 3 dirs with globbed cacheDependency expanding to duplicates', + 'getCacheDirectoriesPaths yarn v%s should return 2 dirs with globbed cacheDependency expanding to duplicates', async version => { let dirNo = 1; getCommandOutputSpy.mockImplementation((command: string) => @@ -269,11 +296,7 @@ two supportedPackageManagers.yarn, '/tmp/**/file' ); - expect(dirs).toEqual([ - `file_${version}_1`, - `file_${version}_2`, - `file_${version}_3` - ]); + expect(dirs).toEqual([`file_${version}_1`, `file_${version}_2`]); } ); diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 6b045c6df..6fa2cf895 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -60434,7 +60434,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoriesPaths = exports.expandCacheDependencyPath = exports.getPackageManagerInfo = exports.getCommandOutputGuarded = exports.getCommandOutput = exports.supportedPackageManagers = exports.yarn2GetCacheFolderCommand = exports.yarn1GetCacheFolderCommand = exports.pnpmGetCacheFolderCommand = exports.npmGetCacheFolderCommand = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoriesPaths = exports.expandCacheDependencyPath = exports.expandedPatternsMemoized = exports.getPackageManagerInfo = exports.getCommandOutputGuarded = exports.getCommandOutput = exports.supportedPackageManagers = exports.yarn2GetCacheFolderCommand = exports.yarn1GetCacheFolderCommand = exports.pnpmGetCacheFolderCommand = exports.npmGetCacheFolderCommand = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -60462,7 +60462,7 @@ exports.supportedPackageManagers = { lockFilePatterns: ['yarn.lock'], getCacheFolderPath: (projectDir) => __awaiter(void 0, void 0, void 0, function* () { const yarnVersion = yield exports.getCommandOutputGuarded(`yarn --version`, 'Could not retrieve version of yarn', projectDir); - core.debug(`Consumed yarn version is ${yarnVersion}`); + core.debug(`Consumed yarn version is ${yarnVersion} (working dir: "${projectDir}")`); const stdOut = yarnVersion.startsWith('1.') ? yield exports.getCommandOutput(exports.yarn1GetCacheFolderCommand, projectDir) : yield exports.getCommandOutput(exports.yarn2GetCacheFolderCommand, projectDir); @@ -60507,10 +60507,27 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void } }); exports.getPackageManagerInfo = getPackageManagerInfo; +exports.expandedPatternsMemoized = {}; +/** + * Wrapper around `glob.create(pattern).glob()` with the memoization + * @param pattern is expected to be a globed path + * @return list of files or directories expanded from glob + */ const globPatternToArray = (pattern) => __awaiter(void 0, void 0, void 0, function* () { + const memoized = exports.expandedPatternsMemoized[pattern]; + if (memoized) + return Promise.resolve(memoized); const globber = yield glob.create(pattern); - return globber.glob(); + const expanded = yield globber.glob(); + exports.expandedPatternsMemoized[pattern] = expanded; + return expanded; }); +/** + * Expands (converts) the string input `cache-dependency-path` to list of files' paths + * First it breaks the input by new lines and then expand glob patterns if any + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * @return list of files on which the cache depends + */ const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { const multilinePaths = cacheDependencyPath .split(/\r?\n/) @@ -60521,26 +60538,55 @@ const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, voi return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); }); exports.expandCacheDependencyPath = expandCacheDependencyPath; -const cacheDependencyPathToCacheFolderPath = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const cacheDependencyPathDirectory = path_1.default.dirname(cacheDependencyPath); - const cacheFolderPath = fs_1.default.existsSync(cacheDependencyPathDirectory) && - fs_1.default.lstatSync(cacheDependencyPathDirectory).isDirectory() - ? yield packageManagerInfo.getCacheFolderPath(cacheDependencyPathDirectory) - : yield packageManagerInfo.getCacheFolderPath(); - core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath} (derived from cache-dependency-path: "${cacheDependencyPath}")`); +/** + * Converts dependency file to the directory it resides in and ensures the directory exists + * @param cacheDependencyPath - file name + * @return either directory containing file or null + */ +const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { + const projectDirectory = path_1.default.dirname(cacheDependencyPath); + if (fs_1.default.existsSync(projectDirectory) && + fs_1.default.lstatSync(projectDirectory).isDirectory()) { + core.debug(`Project directory "${projectDirectory}" derived from cache-dependency-path: "${cacheDependencyPath}"`); + return projectDirectory; + } + else { + core.debug(`No project directory found for cache-dependency-path: "${cacheDependencyPath}", will be skipped`); + return null; + } +}; +/** + * Expands (converts) the string input `cache-dependency-path` to list of directories that + * may be project roots + * @param cacheDependencyPath + * @return list of directories and possible + */ +const cacheDependencyPathToProjectsDirectories = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const cacheDependenciesPaths = yield exports.expandCacheDependencyPath(cacheDependencyPath); + const existingDirectories = cacheDependenciesPaths + .map(cacheDependencyPath => cacheDependencyPathToProjectDirectory(cacheDependencyPath)) + .filter(path => path !== null); + if (existingDirectories.length === 0) + throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); + // uniq + return existingDirectories.filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i); +}); +const projectDirectoryToCacheFolderPath = (packageManagerInfo, projectDirectory) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(projectDirectory); + core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); return cacheFolderPath; }); -const cacheDependenciesPathsToCacheFoldersPaths = (packageManagerInfo, cacheDependenciesPaths) => __awaiter(void 0, void 0, void 0, function* () { - const cacheFoldersPaths = yield Promise.all(cacheDependenciesPaths.map(cacheDependencyPath => cacheDependencyPathToCacheFolderPath(packageManagerInfo, cacheDependencyPath))); +const projectDirectoriesToCacheFoldersPaths = (packageManagerInfo, projectDirectories) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory))); return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); }); const cacheDependencyPathToCacheFoldersPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const cacheDependenciesPaths = yield exports.expandCacheDependencyPath(cacheDependencyPath); - return cacheDependenciesPathsToCacheFoldersPaths(packageManagerInfo, cacheDependenciesPaths); + const projectDirectories = yield cacheDependencyPathToProjectsDirectories(cacheDependencyPath); + return projectDirectoriesToCacheFoldersPaths(packageManagerInfo, projectDirectories); }); const cacheFoldersPathsForRoot = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(); - core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath}`); + core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the root directory`); return [cacheFolderPath]; }); const getCacheDirectoriesPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { diff --git a/dist/setup/index.js b/dist/setup/index.js index 7230bd041..57163eb8f 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71216,7 +71216,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoriesPaths = exports.expandCacheDependencyPath = exports.getPackageManagerInfo = exports.getCommandOutputGuarded = exports.getCommandOutput = exports.supportedPackageManagers = exports.yarn2GetCacheFolderCommand = exports.yarn1GetCacheFolderCommand = exports.pnpmGetCacheFolderCommand = exports.npmGetCacheFolderCommand = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoriesPaths = exports.expandCacheDependencyPath = exports.expandedPatternsMemoized = exports.getPackageManagerInfo = exports.getCommandOutputGuarded = exports.getCommandOutput = exports.supportedPackageManagers = exports.yarn2GetCacheFolderCommand = exports.yarn1GetCacheFolderCommand = exports.pnpmGetCacheFolderCommand = exports.npmGetCacheFolderCommand = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -71244,7 +71244,7 @@ exports.supportedPackageManagers = { lockFilePatterns: ['yarn.lock'], getCacheFolderPath: (projectDir) => __awaiter(void 0, void 0, void 0, function* () { const yarnVersion = yield exports.getCommandOutputGuarded(`yarn --version`, 'Could not retrieve version of yarn', projectDir); - core.debug(`Consumed yarn version is ${yarnVersion}`); + core.debug(`Consumed yarn version is ${yarnVersion} (working dir: "${projectDir}")`); const stdOut = yarnVersion.startsWith('1.') ? yield exports.getCommandOutput(exports.yarn1GetCacheFolderCommand, projectDir) : yield exports.getCommandOutput(exports.yarn2GetCacheFolderCommand, projectDir); @@ -71289,10 +71289,27 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void } }); exports.getPackageManagerInfo = getPackageManagerInfo; +exports.expandedPatternsMemoized = {}; +/** + * Wrapper around `glob.create(pattern).glob()` with the memoization + * @param pattern is expected to be a globed path + * @return list of files or directories expanded from glob + */ const globPatternToArray = (pattern) => __awaiter(void 0, void 0, void 0, function* () { + const memoized = exports.expandedPatternsMemoized[pattern]; + if (memoized) + return Promise.resolve(memoized); const globber = yield glob.create(pattern); - return globber.glob(); + const expanded = yield globber.glob(); + exports.expandedPatternsMemoized[pattern] = expanded; + return expanded; }); +/** + * Expands (converts) the string input `cache-dependency-path` to list of files' paths + * First it breaks the input by new lines and then expand glob patterns if any + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * @return list of files on which the cache depends + */ const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { const multilinePaths = cacheDependencyPath .split(/\r?\n/) @@ -71303,26 +71320,55 @@ const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, voi return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); }); exports.expandCacheDependencyPath = expandCacheDependencyPath; -const cacheDependencyPathToCacheFolderPath = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const cacheDependencyPathDirectory = path_1.default.dirname(cacheDependencyPath); - const cacheFolderPath = fs_1.default.existsSync(cacheDependencyPathDirectory) && - fs_1.default.lstatSync(cacheDependencyPathDirectory).isDirectory() - ? yield packageManagerInfo.getCacheFolderPath(cacheDependencyPathDirectory) - : yield packageManagerInfo.getCacheFolderPath(); - core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath} (derived from cache-dependency-path: "${cacheDependencyPath}")`); +/** + * Converts dependency file to the directory it resides in and ensures the directory exists + * @param cacheDependencyPath - file name + * @return either directory containing file or null + */ +const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { + const projectDirectory = path_1.default.dirname(cacheDependencyPath); + if (fs_1.default.existsSync(projectDirectory) && + fs_1.default.lstatSync(projectDirectory).isDirectory()) { + core.debug(`Project directory "${projectDirectory}" derived from cache-dependency-path: "${cacheDependencyPath}"`); + return projectDirectory; + } + else { + core.debug(`No project directory found for cache-dependency-path: "${cacheDependencyPath}", will be skipped`); + return null; + } +}; +/** + * Expands (converts) the string input `cache-dependency-path` to list of directories that + * may be project roots + * @param cacheDependencyPath + * @return list of directories and possible + */ +const cacheDependencyPathToProjectsDirectories = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const cacheDependenciesPaths = yield exports.expandCacheDependencyPath(cacheDependencyPath); + const existingDirectories = cacheDependenciesPaths + .map(cacheDependencyPath => cacheDependencyPathToProjectDirectory(cacheDependencyPath)) + .filter(path => path !== null); + if (existingDirectories.length === 0) + throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); + // uniq + return existingDirectories.filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i); +}); +const projectDirectoryToCacheFolderPath = (packageManagerInfo, projectDirectory) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(projectDirectory); + core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); return cacheFolderPath; }); -const cacheDependenciesPathsToCacheFoldersPaths = (packageManagerInfo, cacheDependenciesPaths) => __awaiter(void 0, void 0, void 0, function* () { - const cacheFoldersPaths = yield Promise.all(cacheDependenciesPaths.map(cacheDependencyPath => cacheDependencyPathToCacheFolderPath(packageManagerInfo, cacheDependencyPath))); +const projectDirectoriesToCacheFoldersPaths = (packageManagerInfo, projectDirectories) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory))); return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); }); const cacheDependencyPathToCacheFoldersPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const cacheDependenciesPaths = yield exports.expandCacheDependencyPath(cacheDependencyPath); - return cacheDependenciesPathsToCacheFoldersPaths(packageManagerInfo, cacheDependenciesPaths); + const projectDirectories = yield cacheDependencyPathToProjectsDirectories(cacheDependencyPath); + return projectDirectoriesToCacheFoldersPaths(packageManagerInfo, projectDirectories); }); const cacheFoldersPathsForRoot = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(); - core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath}`); + core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the root directory`); return [cacheFolderPath]; }); const getCacheDirectoriesPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 9c7f28272..2c41af604 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -51,7 +51,9 @@ export const supportedPackageManagers: SupportedPackageManagers = { projectDir ); - core.debug(`Consumed yarn version is ${yarnVersion}`); + core.debug( + `Consumed yarn version is ${yarnVersion} (working dir: "${projectDir}")` + ); const stdOut = yarnVersion.startsWith('1.') ? await getCommandOutput(yarn1GetCacheFolderCommand, projectDir) @@ -110,12 +112,27 @@ export const getPackageManagerInfo = async (packageManager: string) => { return null; } }; - +export const expandedPatternsMemoized: Record = {}; +/** + * Wrapper around `glob.create(pattern).glob()` with the memoization + * @param pattern is expected to be a globed path + * @return list of files or directories expanded from glob + */ const globPatternToArray = async (pattern: string): Promise => { + const memoized = expandedPatternsMemoized[pattern]; + if (memoized) return Promise.resolve(memoized); const globber = await glob.create(pattern); - return globber.glob(); + const expanded = await globber.glob(); + expandedPatternsMemoized[pattern] = expanded; + return expanded; }; +/** + * Expands (converts) the string input `cache-dependency-path` to list of files' paths + * First it breaks the input by new lines and then expand glob patterns if any + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * @return list of files on which the cache depends + */ export const expandCacheDependencyPath = async ( cacheDependencyPath: string ): Promise => { @@ -130,52 +147,98 @@ export const expandCacheDependencyPath = async ( return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); }; -const cacheDependencyPathToCacheFolderPath = async ( - packageManagerInfo: PackageManagerInfo, +/** + * Converts dependency file to the directory it resides in and ensures the directory exists + * @param cacheDependencyPath - file name + * @return either directory containing file or null + */ +const cacheDependencyPathToProjectDirectory = ( cacheDependencyPath: string -): Promise => { - const cacheDependencyPathDirectory = path.dirname(cacheDependencyPath); - const cacheFolderPath = - fs.existsSync(cacheDependencyPathDirectory) && - fs.lstatSync(cacheDependencyPathDirectory).isDirectory() - ? await packageManagerInfo.getCacheFolderPath( - cacheDependencyPathDirectory - ) - : await packageManagerInfo.getCacheFolderPath(); +): string | null => { + const projectDirectory = path.dirname(cacheDependencyPath); + if ( + fs.existsSync(projectDirectory) && + fs.lstatSync(projectDirectory).isDirectory() + ) { + core.debug( + `Project directory "${projectDirectory}" derived from cache-dependency-path: "${cacheDependencyPath}"` + ); + return projectDirectory; + } else { + core.debug( + `No project directory found for cache-dependency-path: "${cacheDependencyPath}", will be skipped` + ); + return null; + } +}; - core.debug( - `${packageManagerInfo.name} path is ${cacheFolderPath} (derived from cache-dependency-path: "${cacheDependencyPath}")` +/** + * Expands (converts) the string input `cache-dependency-path` to list of directories that + * may be project roots + * @param cacheDependencyPath + * @return list of directories and possible + */ +const cacheDependencyPathToProjectsDirectories = async ( + cacheDependencyPath: string +): Promise => { + const cacheDependenciesPaths = await expandCacheDependencyPath( + cacheDependencyPath ); + const existingDirectories: string[] = cacheDependenciesPaths + .map(cacheDependencyPath => + cacheDependencyPathToProjectDirectory(cacheDependencyPath) + ) + .filter(path => path !== null) as string[]; + + if (existingDirectories.length === 0) + throw Error( + 'No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"' + ); + + // uniq + return existingDirectories.filter( + (cachePath, i, result) => + cachePath != null && result.indexOf(cachePath) === i + ); +}; + +const projectDirectoryToCacheFolderPath = async ( + packageManagerInfo: PackageManagerInfo, + projectDirectory: string +): Promise => { + const cacheFolderPath = await packageManagerInfo.getCacheFolderPath( + projectDirectory + ); + core.debug( + `${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"` + ); return cacheFolderPath; }; -const cacheDependenciesPathsToCacheFoldersPaths = async ( + +const projectDirectoriesToCacheFoldersPaths = async ( packageManagerInfo: PackageManagerInfo, - cacheDependenciesPaths: string[] + projectDirectories: string[] ): Promise => { const cacheFoldersPaths = await Promise.all( - cacheDependenciesPaths.map(cacheDependencyPath => - cacheDependencyPathToCacheFolderPath( - packageManagerInfo, - cacheDependencyPath - ) + projectDirectories.map(projectDirectory => + projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory) ) ); return cacheFoldersPaths.filter( (cachePath, i, result) => result.indexOf(cachePath) === i ); }; - const cacheDependencyPathToCacheFoldersPaths = async ( packageManagerInfo: PackageManagerInfo, cacheDependencyPath: string ): Promise => { - const cacheDependenciesPaths = await expandCacheDependencyPath( + const projectDirectories = await cacheDependencyPathToProjectsDirectories( cacheDependencyPath ); - return cacheDependenciesPathsToCacheFoldersPaths( + return projectDirectoriesToCacheFoldersPaths( packageManagerInfo, - cacheDependenciesPaths + projectDirectories ); }; @@ -183,7 +246,9 @@ const cacheFoldersPathsForRoot = async ( packageManagerInfo: PackageManagerInfo ): Promise => { const cacheFolderPath = await packageManagerInfo.getCacheFolderPath(); - core.debug(`${packageManagerInfo.name} path is ${cacheFolderPath}`); + core.debug( + `${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the root directory` + ); return [cacheFolderPath]; }; From 7406bf5e76ff06292d3605d9a3884a026ab7fe08 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Mon, 22 May 2023 10:58:01 +0200 Subject: [PATCH 13/21] Changes requests --- dist/cache-save/index.js | 55 ++++++++++++++++++++++++++------- dist/setup/index.js | 53 ++++++++++++++++++++++++++------ src/cache-save.ts | 3 +- src/cache-utils.ts | 66 ++++++++++++++++++++++++++++------------ 4 files changed, 135 insertions(+), 42 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 6fa2cf895..631e6d47d 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -60375,7 +60375,7 @@ const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, func core.debug(`Caching for '${packageManager}' is not supported`); return; } - // TODO: core.getInput has a bug - it can return undefined despite its definition + // TODO: core.getInput has a bug - it can return undefined despite its definition (tests only?) // export declare function getInput(name: string, options?: InputOptions): string; const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; const cachePaths = yield cache_utils_1.getCacheDirectoriesPaths(packageManagerInfo, cacheDependencyPath); @@ -60507,6 +60507,10 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void } }); exports.getPackageManagerInfo = getPackageManagerInfo; +/** + * glob expanding memoized because it involves potentially very deep + * traversing through the directories tree + */ exports.expandedPatternsMemoized = {}; /** * Wrapper around `glob.create(pattern).glob()` with the memoization @@ -60539,9 +60543,9 @@ const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, voi }); exports.expandCacheDependencyPath = expandCacheDependencyPath; /** - * Converts dependency file to the directory it resides in and ensures the directory exists - * @param cacheDependencyPath - file name - * @return either directory containing file or null + * Converts dependency file path to the directory it resides in and ensures the directory exists + * @param cacheDependencyPath - a file name path + * @return either directory containing the file or null */ const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { const projectDirectory = path_1.default.dirname(cacheDependencyPath); @@ -60558,7 +60562,8 @@ const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots - * @param cacheDependencyPath + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of directories and possible */ const cacheDependencyPathToProjectsDirectories = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { @@ -60566,29 +60571,57 @@ const cacheDependencyPathToProjectsDirectories = (cacheDependencyPath) => __awai const existingDirectories = cacheDependenciesPaths .map(cacheDependencyPath => cacheDependencyPathToProjectDirectory(cacheDependencyPath)) .filter(path => path !== null); + // if user explicitly pointed out some file, but it does not exist it is definitely + // not he wanted, thus we should throw an error not trying to workaround with unexpected + // result to the whole build if (existingDirectories.length === 0) throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); - // uniq + // uniq in order to do not traverse the same directories during the further processing return existingDirectories.filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i); }); +/** + * Utility function to be used from within `map` + * Finds the cache directories configured for the project directory + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param projectDirectory - the string pointing out to a project dir (i.e. directory with its own .yarnrc) + * @return list of directories to be cached according to the project configuration in the directory + */ const projectDirectoryToCacheFolderPath = (packageManagerInfo, projectDirectory) => __awaiter(void 0, void 0, void 0, function* () { const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(projectDirectory); core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); return cacheFolderPath; }); -const projectDirectoriesToCacheFoldersPaths = (packageManagerInfo, projectDirectories) => __awaiter(void 0, void 0, void 0, function* () { - const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory))); - return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); -}); +/** + * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is not empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` + * @return list of files on which the cache depends + */ const cacheDependencyPathToCacheFoldersPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { const projectDirectories = yield cacheDependencyPathToProjectsDirectories(cacheDependencyPath); - return projectDirectoriesToCacheFoldersPaths(packageManagerInfo, projectDirectories); + const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory))); + // uniq in order to do not cache the same directories twice + return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); }); +/** + * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @return list of files on which the cache depends + */ const cacheFoldersPathsForRoot = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(); core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the root directory`); return [cacheFolderPath]; }); +/** + * Main function to find the cache directories configured for the repo + * currently it handles only the case of PM=yarn && cacheDependencyPath is not empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` + * @return list of files on which the cache depends + */ const getCacheDirectoriesPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { // TODO: multiple directories limited to yarn so far return packageManagerInfo === exports.supportedPackageManagers.yarn diff --git a/dist/setup/index.js b/dist/setup/index.js index 57163eb8f..23abc1609 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71289,6 +71289,10 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void } }); exports.getPackageManagerInfo = getPackageManagerInfo; +/** + * glob expanding memoized because it involves potentially very deep + * traversing through the directories tree + */ exports.expandedPatternsMemoized = {}; /** * Wrapper around `glob.create(pattern).glob()` with the memoization @@ -71321,9 +71325,9 @@ const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, voi }); exports.expandCacheDependencyPath = expandCacheDependencyPath; /** - * Converts dependency file to the directory it resides in and ensures the directory exists - * @param cacheDependencyPath - file name - * @return either directory containing file or null + * Converts dependency file path to the directory it resides in and ensures the directory exists + * @param cacheDependencyPath - a file name path + * @return either directory containing the file or null */ const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { const projectDirectory = path_1.default.dirname(cacheDependencyPath); @@ -71340,7 +71344,8 @@ const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots - * @param cacheDependencyPath + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of directories and possible */ const cacheDependencyPathToProjectsDirectories = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { @@ -71348,29 +71353,57 @@ const cacheDependencyPathToProjectsDirectories = (cacheDependencyPath) => __awai const existingDirectories = cacheDependenciesPaths .map(cacheDependencyPath => cacheDependencyPathToProjectDirectory(cacheDependencyPath)) .filter(path => path !== null); + // if user explicitly pointed out some file, but it does not exist it is definitely + // not he wanted, thus we should throw an error not trying to workaround with unexpected + // result to the whole build if (existingDirectories.length === 0) throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); - // uniq + // uniq in order to do not traverse the same directories during the further processing return existingDirectories.filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i); }); +/** + * Utility function to be used from within `map` + * Finds the cache directories configured for the project directory + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param projectDirectory - the string pointing out to a project dir (i.e. directory with its own .yarnrc) + * @return list of directories to be cached according to the project configuration in the directory + */ const projectDirectoryToCacheFolderPath = (packageManagerInfo, projectDirectory) => __awaiter(void 0, void 0, void 0, function* () { const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(projectDirectory); core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); return cacheFolderPath; }); -const projectDirectoriesToCacheFoldersPaths = (packageManagerInfo, projectDirectories) => __awaiter(void 0, void 0, void 0, function* () { - const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory))); - return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); -}); +/** + * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is not empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` + * @return list of files on which the cache depends + */ const cacheDependencyPathToCacheFoldersPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { const projectDirectories = yield cacheDependencyPathToProjectsDirectories(cacheDependencyPath); - return projectDirectoriesToCacheFoldersPaths(packageManagerInfo, projectDirectories); + const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory))); + // uniq in order to do not cache the same directories twice + return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); }); +/** + * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @return list of files on which the cache depends + */ const cacheFoldersPathsForRoot = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(); core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the root directory`); return [cacheFolderPath]; }); +/** + * Main function to find the cache directories configured for the repo + * currently it handles only the case of PM=yarn && cacheDependencyPath is not empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` + * @return list of files on which the cache depends + */ const getCacheDirectoriesPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { // TODO: multiple directories limited to yarn so far return packageManagerInfo === exports.supportedPackageManagers.yarn diff --git a/src/cache-save.ts b/src/cache-save.ts index 660ec37c7..a54a741d0 100644 --- a/src/cache-save.ts +++ b/src/cache-save.ts @@ -1,6 +1,5 @@ import * as core from '@actions/core'; import * as cache from '@actions/cache'; -import fs from 'fs'; import {State} from './constants'; import {getCacheDirectoriesPaths, getPackageManagerInfo} from './cache-utils'; @@ -31,7 +30,7 @@ const cachePackages = async (packageManager: string) => { return; } - // TODO: core.getInput has a bug - it can return undefined despite its definition + // TODO: core.getInput has a bug - it can return undefined despite its definition (tests only?) // export declare function getInput(name: string, options?: InputOptions): string; const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; const cachePaths = await getCacheDirectoriesPaths( diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 2c41af604..4fc69717a 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -112,6 +112,11 @@ export const getPackageManagerInfo = async (packageManager: string) => { return null; } }; + +/** + * glob expanding memoized because it involves potentially very deep + * traversing through the directories tree + */ export const expandedPatternsMemoized: Record = {}; /** * Wrapper around `glob.create(pattern).glob()` with the memoization @@ -148,9 +153,9 @@ export const expandCacheDependencyPath = async ( }; /** - * Converts dependency file to the directory it resides in and ensures the directory exists - * @param cacheDependencyPath - file name - * @return either directory containing file or null + * Converts dependency file path to the directory it resides in and ensures the directory exists + * @param cacheDependencyPath - a file name path + * @return either directory containing the file or null */ const cacheDependencyPathToProjectDirectory = ( cacheDependencyPath: string @@ -175,7 +180,8 @@ const cacheDependencyPathToProjectDirectory = ( /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots - * @param cacheDependencyPath + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of directories and possible */ const cacheDependencyPathToProjectsDirectories = async ( @@ -191,18 +197,28 @@ const cacheDependencyPathToProjectsDirectories = async ( ) .filter(path => path !== null) as string[]; + // if user explicitly pointed out some file, but it does not exist it is definitely + // not he wanted, thus we should throw an error not trying to workaround with unexpected + // result to the whole build if (existingDirectories.length === 0) throw Error( 'No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"' ); - // uniq + // uniq in order to do not traverse the same directories during the further processing return existingDirectories.filter( (cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i ); }; +/** + * Utility function to be used from within `map` + * Finds the cache directories configured for the project directory + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param projectDirectory - the string pointing out to a project dir (i.e. directory with its own .yarnrc) + * @return list of directories to be cached according to the project configuration in the directory + */ const projectDirectoryToCacheFolderPath = async ( packageManagerInfo: PackageManagerInfo, projectDirectory: string @@ -216,32 +232,36 @@ const projectDirectoryToCacheFolderPath = async ( return cacheFolderPath; }; -const projectDirectoriesToCacheFoldersPaths = async ( +/** + * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is not empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` + * @return list of files on which the cache depends + */ +const cacheDependencyPathToCacheFoldersPaths = async ( packageManagerInfo: PackageManagerInfo, - projectDirectories: string[] + cacheDependencyPath: string ): Promise => { + const projectDirectories = await cacheDependencyPathToProjectsDirectories( + cacheDependencyPath + ); const cacheFoldersPaths = await Promise.all( projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory) ) ); + // uniq in order to do not cache the same directories twice return cacheFoldersPaths.filter( (cachePath, i, result) => result.indexOf(cachePath) === i ); }; -const cacheDependencyPathToCacheFoldersPaths = async ( - packageManagerInfo: PackageManagerInfo, - cacheDependencyPath: string -): Promise => { - const projectDirectories = await cacheDependencyPathToProjectsDirectories( - cacheDependencyPath - ); - return projectDirectoriesToCacheFoldersPaths( - packageManagerInfo, - projectDirectories - ); -}; +/** + * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @return list of files on which the cache depends + */ const cacheFoldersPathsForRoot = async ( packageManagerInfo: PackageManagerInfo ): Promise => { @@ -252,6 +272,14 @@ const cacheFoldersPathsForRoot = async ( return [cacheFolderPath]; }; +/** + * Main function to find the cache directories configured for the repo + * currently it handles only the case of PM=yarn && cacheDependencyPath is not empty + * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM + * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns + * expected to be the result of `core.getInput('cache-dependency-path')` + * @return list of files on which the cache depends + */ export const getCacheDirectoriesPaths = async ( packageManagerInfo: PackageManagerInfo, cacheDependencyPath: string From 9ddc512bc1770f4522d2a1614b4de57894596f4c Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Tue, 30 May 2023 14:15:01 +0200 Subject: [PATCH 14/21] Apply fixes --- __tests__/cache-restore.test.ts | 8 +- __tests__/cache-save.test.ts | 28 ++--- __tests__/cache-utils.test.ts | 76 ++++--------- dist/cache-save/index.js | 143 +++++++++---------------- dist/setup/index.js | 143 +++++++++---------------- src/cache-restore.ts | 4 +- src/cache-save.ts | 4 +- src/cache-utils.ts | 184 +++++++++++--------------------- 8 files changed, 193 insertions(+), 397 deletions(-) diff --git a/__tests__/cache-restore.test.ts b/__tests__/cache-restore.test.ts index ba20a22d8..86dff3f32 100644 --- a/__tests__/cache-restore.test.ts +++ b/__tests__/cache-restore.test.ts @@ -32,13 +32,13 @@ describe('cache-restore', () => { function findCacheFolder(command: string) { switch (command) { - case utils.npmGetCacheFolderCommand: + case 'npm config get cache': return npmCachePath; - case utils.pnpmGetCacheFolderCommand: + case 'pnpm store path --silent': return pnpmCachePath; - case utils.yarn1GetCacheFolderCommand: + case 'yarn cache dir': return yarn1CachePath; - case utils.yarn2GetCacheFolderCommand: + case 'yarn config get cacheFolder': return yarn2CachePath; default: return 'packge/not/found'; diff --git a/__tests__/cache-save.test.ts b/__tests__/cache-save.test.ts index 4fc997920..c84621c53 100644 --- a/__tests__/cache-save.test.ts +++ b/__tests__/cache-save.test.ts @@ -118,13 +118,10 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); expect(debugSpy).toHaveBeenCalledWith( - 'Project directory "." derived from cache-dependency-path: ""' + 'Consumed yarn version is 1.2.3 (working dir: "")' ); expect(debugSpy).toHaveBeenCalledWith( - 'Consumed yarn version is 1.2.3 (working dir: ".")' - ); - expect(debugSpy).toHaveBeenCalledWith( - 'yarn\'s cache folder "/some/random/path/yarn1" configured for the directory "."' + 'yarn\'s cache folder "/some/random/path/yarn1" configured for the root directory' ); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` @@ -145,13 +142,10 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); expect(debugSpy).toHaveBeenCalledWith( - 'Project directory "." derived from cache-dependency-path: ""' - ); - expect(debugSpy).toHaveBeenCalledWith( - 'Consumed yarn version is 2.2.3 (working dir: ".")' + 'Consumed yarn version is 2.2.3 (working dir: "")' ); expect(debugSpy).toHaveBeenCalledWith( - 'yarn\'s cache folder "/some/random/path/yarn2" configured for the directory "."' + 'yarn\'s cache folder "/some/random/path/yarn2" configured for the root directory' ); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` @@ -218,13 +212,10 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); expect(debugSpy).toHaveBeenCalledWith( - 'Project directory "." derived from cache-dependency-path: ""' + 'Consumed yarn version is 1.2.3 (working dir: "")' ); expect(debugSpy).toHaveBeenCalledWith( - 'Consumed yarn version is 1.2.3 (working dir: ".")' - ); - expect(debugSpy).toHaveBeenCalledWith( - 'yarn\'s cache folder "/some/random/path/yarn1" configured for the directory "."' + 'yarn\'s cache folder "/some/random/path/yarn1" configured for the root directory' ); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` @@ -255,13 +246,10 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(2); expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); expect(debugSpy).toHaveBeenCalledWith( - 'Project directory "." derived from cache-dependency-path: ""' - ); - expect(debugSpy).toHaveBeenCalledWith( - 'Consumed yarn version is 2.2.3 (working dir: ".")' + 'Consumed yarn version is 2.2.3 (working dir: "")' ); expect(debugSpy).toHaveBeenCalledWith( - 'yarn\'s cache folder "/some/random/path/yarn2" configured for the directory "."' + 'yarn\'s cache folder "/some/random/path/yarn2" configured for the root directory' ); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` diff --git a/__tests__/cache-utils.test.ts b/__tests__/cache-utils.test.ts index 789d3ba61..da9c793bc 100644 --- a/__tests__/cache-utils.test.ts +++ b/__tests__/cache-utils.test.ts @@ -7,8 +7,7 @@ import { isCacheFeatureAvailable, supportedPackageManagers, getCommandOutput, - expandCacheDependencyPath, - expandedPatternsMemoized + memoizedCacheDependencies } from '../src/cache-utils'; import fs from 'fs'; import * as cacheUtils from '../src/cache-utils'; @@ -106,8 +105,8 @@ describe('cache-utils', () => { MockGlobber.create(['/foo', '/bar']) ); - Object.keys(expandedPatternsMemoized).forEach( - key => delete expandedPatternsMemoized[key] + Object.keys(memoizedCacheDependencies).forEach( + key => delete memoizedCacheDependencies[key] ); }); @@ -117,44 +116,6 @@ describe('cache-utils', () => { globCreateSpy.mockRestore(); }); - it('expandCacheDependencyPath should handle one line', async () => { - expect(await expandCacheDependencyPath('one')).toEqual(['one']); - }); - - it('expandCacheDependencyPath should handle one line glob', async () => { - globCreateSpy.mockImplementation( - (pattern: string): Promise => - MockGlobber.create(['one', 'two']) - ); - expect(await expandCacheDependencyPath('**')).toEqual(['one', 'two']); - }); - - it('expandCacheDependencyPath should handle multiple lines', async () => { - const lines = ` - one -two - - `; - expect(await expandCacheDependencyPath(lines)).toEqual(['one', 'two']); - }); - - it('expandCacheDependencyPath should handle multiple globs', async () => { - const lines = ` - one -** - - `; - globCreateSpy.mockImplementation( - (pattern: string): Promise => - MockGlobber.create(['two', 'three']) - ); - expect(await expandCacheDependencyPath(lines)).toEqual([ - 'one', - 'two', - 'three' - ]); - }); - it.each([ [supportedPackageManagers.npm, ''], [supportedPackageManagers.npm, '/dir/file.lock'], @@ -167,7 +128,7 @@ two async (packageManagerInfo, cacheDependency) => { getCommandOutputSpy.mockImplementation(() => 'foo'); - const dirs = await cacheUtils.getCacheDirectoriesPaths( + const dirs = await cacheUtils.getCacheDirectories( packageManagerInfo, cacheDependency ); @@ -181,7 +142,7 @@ two it('getCacheDirectoriesPaths should return one dir for yarn without cacheDependency', async () => { getCommandOutputSpy.mockImplementation(() => 'foo'); - const dirs = await cacheUtils.getCacheDirectoriesPaths( + const dirs = await cacheUtils.getCacheDirectories( supportedPackageManagers.yarn, '' ); @@ -208,10 +169,7 @@ two ); await expect( - cacheUtils.getCacheDirectoriesPaths( - packageManagerInfo, - cacheDependency - ) + cacheUtils.getCacheDirectories(packageManagerInfo, cacheDependency) ).rejects.toThrow(); //'Could not get cache folder path for /dir'); } ); @@ -234,10 +192,7 @@ two })); await expect( - cacheUtils.getCacheDirectoriesPaths( - packageManagerInfo, - cacheDependency - ) + cacheUtils.getCacheDirectories(packageManagerInfo, cacheDependency) ).rejects.toThrow(); //'Could not get cache folder path for /dir'); } ); @@ -248,7 +203,7 @@ two getCommandOutputSpy.mockImplementationOnce(() => version); getCommandOutputSpy.mockImplementationOnce(() => `foo${version}`); - const dirs = await cacheUtils.getCacheDirectoriesPaths( + const dirs = await cacheUtils.getCacheDirectories( supportedPackageManagers.yarn, '' ); @@ -268,7 +223,7 @@ two MockGlobber.create(['/tmp/dir1/file', '/tmp/dir2/file']) ); - const dirs = await cacheUtils.getCacheDirectoriesPaths( + const dirs = await cacheUtils.getCacheDirectories( supportedPackageManagers.yarn, '/tmp/**/file' ); @@ -292,7 +247,7 @@ two ]) ); - const dirs = await cacheUtils.getCacheDirectoriesPaths( + const dirs = await cacheUtils.getCacheDirectories( supportedPackageManagers.yarn, '/tmp/**/file' ); @@ -318,7 +273,7 @@ two ]) ); - const dirs = await cacheUtils.getCacheDirectoriesPaths( + const dirs = await cacheUtils.getCacheDirectories( supportedPackageManagers.yarn, '/tmp/**/file' ); @@ -367,13 +322,18 @@ two `; globCreateSpy.mockImplementation( (pattern: string): Promise => - MockGlobber.create(['/tmp/dir3/file', '/tmp/dir4/file']) + MockGlobber.create([ + '/tmp/dir1/file', + '/tmp/dir2/file', + '/tmp/dir3/file', + '/tmp/dir4/file' + ]) ); let dirNo = 1; getCommandOutputSpy.mockImplementation((command: string) => command.includes('version') ? version : `file_${version}_${dirNo++}` ); - const dirs = await cacheUtils.getCacheDirectoriesPaths( + const dirs = await cacheUtils.getCacheDirectories( supportedPackageManagers.yarn, cacheDependencyPath ); diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 631e6d47d..b7b72fdec 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -60378,7 +60378,7 @@ const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, func // TODO: core.getInput has a bug - it can return undefined despite its definition (tests only?) // export declare function getInput(name: string, options?: InputOptions): string; const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; - const cachePaths = yield cache_utils_1.getCacheDirectoriesPaths(packageManagerInfo, cacheDependencyPath); + const cachePaths = yield cache_utils_1.getCacheDirectories(packageManagerInfo, cacheDependencyPath); if (cachePaths.length === 0) { throw new Error(`Cache folder paths are not retrieved for ${packageManager} with cache-dependency-path = ${cacheDependencyPath}`); } @@ -60434,38 +60434,33 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoriesPaths = exports.expandCacheDependencyPath = exports.expandedPatternsMemoized = exports.getPackageManagerInfo = exports.getCommandOutputGuarded = exports.getCommandOutput = exports.supportedPackageManagers = exports.yarn2GetCacheFolderCommand = exports.yarn1GetCacheFolderCommand = exports.pnpmGetCacheFolderCommand = exports.npmGetCacheFolderCommand = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectories = exports.memoizedCacheDependencies = exports.getPackageManagerInfo = exports.getCommandOutputNotEmpty = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); const glob = __importStar(__nccwpck_require__(8090)); const path_1 = __importDefault(__nccwpck_require__(1017)); const fs_1 = __importDefault(__nccwpck_require__(7147)); -// for testing purposes -exports.npmGetCacheFolderCommand = 'npm config get cache'; -exports.pnpmGetCacheFolderCommand = 'pnpm store path --silent'; -exports.yarn1GetCacheFolderCommand = 'yarn cache dir'; -exports.yarn2GetCacheFolderCommand = 'yarn config get cacheFolder'; exports.supportedPackageManagers = { npm: { name: 'npm', lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], - getCacheFolderPath: () => exports.getCommandOutputGuarded(exports.npmGetCacheFolderCommand, 'Could not get npm cache folder path') + getCacheFolderPath: () => exports.getCommandOutputNotEmpty('npm config get cache', 'Could not get npm cache folder path') }, pnpm: { name: 'pnpm', lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderPath: () => exports.getCommandOutputGuarded(exports.pnpmGetCacheFolderCommand, 'Could not get pnpm cache folder path') + getCacheFolderPath: () => exports.getCommandOutputNotEmpty('pnpm store path --silent', 'Could not get pnpm cache folder path') }, yarn: { name: 'yarn', lockFilePatterns: ['yarn.lock'], getCacheFolderPath: (projectDir) => __awaiter(void 0, void 0, void 0, function* () { - const yarnVersion = yield exports.getCommandOutputGuarded(`yarn --version`, 'Could not retrieve version of yarn', projectDir); - core.debug(`Consumed yarn version is ${yarnVersion} (working dir: "${projectDir}")`); + const yarnVersion = yield exports.getCommandOutputNotEmpty(`yarn --version`, 'Could not retrieve version of yarn', projectDir); + core.debug(`Consumed yarn version is ${yarnVersion} (working dir: "${projectDir || ''}")`); const stdOut = yarnVersion.startsWith('1.') - ? yield exports.getCommandOutput(exports.yarn1GetCacheFolderCommand, projectDir) - : yield exports.getCommandOutput(exports.yarn2GetCacheFolderCommand, projectDir); + ? yield exports.getCommandOutput('yarn cache dir', projectDir) + : yield exports.getCommandOutput('yarn config get cacheFolder', projectDir); if (!stdOut) { throw new Error(`Could not get yarn cache folder path for ${projectDir}`); } @@ -60484,14 +60479,14 @@ const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, return stdout.trim(); }); exports.getCommandOutput = getCommandOutput; -const getCommandOutputGuarded = (toolCommand, error, cwd) => __awaiter(void 0, void 0, void 0, function* () { +const getCommandOutputNotEmpty = (toolCommand, error, cwd) => __awaiter(void 0, void 0, void 0, function* () { const stdOut = exports.getCommandOutput(toolCommand, cwd); if (!stdOut) { throw new Error(error); } return stdOut; }); -exports.getCommandOutputGuarded = getCommandOutputGuarded; +exports.getCommandOutputNotEmpty = getCommandOutputNotEmpty; const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { if (packageManager === 'npm') { return exports.supportedPackageManagers.npm; @@ -60511,54 +60506,7 @@ exports.getPackageManagerInfo = getPackageManagerInfo; * glob expanding memoized because it involves potentially very deep * traversing through the directories tree */ -exports.expandedPatternsMemoized = {}; -/** - * Wrapper around `glob.create(pattern).glob()` with the memoization - * @param pattern is expected to be a globed path - * @return list of files or directories expanded from glob - */ -const globPatternToArray = (pattern) => __awaiter(void 0, void 0, void 0, function* () { - const memoized = exports.expandedPatternsMemoized[pattern]; - if (memoized) - return Promise.resolve(memoized); - const globber = yield glob.create(pattern); - const expanded = yield globber.glob(); - exports.expandedPatternsMemoized[pattern] = expanded; - return expanded; -}); -/** - * Expands (converts) the string input `cache-dependency-path` to list of files' paths - * First it breaks the input by new lines and then expand glob patterns if any - * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns - * @return list of files on which the cache depends - */ -const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const multilinePaths = cacheDependencyPath - .split(/\r?\n/) - .map(path => path.trim()) - .filter(path => Boolean(path)); - const expandedPathsPromises = multilinePaths.map(path => path.includes('*') ? globPatternToArray(path) : Promise.resolve([path])); - const expandedPaths = yield Promise.all(expandedPathsPromises); - return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); -}); -exports.expandCacheDependencyPath = expandCacheDependencyPath; -/** - * Converts dependency file path to the directory it resides in and ensures the directory exists - * @param cacheDependencyPath - a file name path - * @return either directory containing the file or null - */ -const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { - const projectDirectory = path_1.default.dirname(cacheDependencyPath); - if (fs_1.default.existsSync(projectDirectory) && - fs_1.default.lstatSync(projectDirectory).isDirectory()) { - core.debug(`Project directory "${projectDirectory}" derived from cache-dependency-path: "${cacheDependencyPath}"`); - return projectDirectory; - } - else { - core.debug(`No project directory found for cache-dependency-path: "${cacheDependencyPath}", will be skipped`); - return null; - } -}; +exports.memoizedCacheDependencies = {}; /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots @@ -60566,69 +60514,76 @@ const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of directories and possible */ -const cacheDependencyPathToProjectsDirectories = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const cacheDependenciesPaths = yield exports.expandCacheDependencyPath(cacheDependencyPath); +const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + let cacheDependenciesPaths; + // memoize unglobbed paths to avoid traversing FS + const memoized = exports.memoizedCacheDependencies[cacheDependencyPath]; + if (memoized) { + cacheDependenciesPaths = memoized; + } + else { + cacheDependenciesPaths = (yield glob + .create(cacheDependencyPath) + .then(globber => globber.glob())) || ['']; + exports.memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; + } const existingDirectories = cacheDependenciesPaths - .map(cacheDependencyPath => cacheDependencyPathToProjectDirectory(cacheDependencyPath)) - .filter(path => path !== null); + .map(cacheDependencyPath => path_1.default.dirname(cacheDependencyPath)) + // uniq in order to do not traverse the same directories during the further processing + .filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i) + .filter(directory => fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected // result to the whole build if (existingDirectories.length === 0) throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); - // uniq in order to do not traverse the same directories during the further processing - return existingDirectories.filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i); + return existingDirectories; }); /** - * Utility function to be used from within `map` - * Finds the cache directories configured for the project directory - * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM - * @param projectDirectory - the string pointing out to a project dir (i.e. directory with its own .yarnrc) - * @return list of directories to be cached according to the project configuration in the directory - */ -const projectDirectoryToCacheFolderPath = (packageManagerInfo, projectDirectory) => __awaiter(void 0, void 0, void 0, function* () { - const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(projectDirectory); - core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); - return cacheFolderPath; -}); -/** - * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is not empty + * Finds the cache directories configured for the repo if cache-dependency-path is not empty * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of files on which the cache depends */ -const cacheDependencyPathToCacheFoldersPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const projectDirectories = yield cacheDependencyPathToProjectsDirectories(cacheDependencyPath); - const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory))); +const getCacheDirectoriesFromCacheDependencyPath = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const projectDirectories = yield getProjectDirectoriesFromCacheDependencyPath(cacheDependencyPath); + const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => packageManagerInfo + .getCacheFolderPath(projectDirectory) + .then(cacheFolderPath => { + core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); + return cacheFolderPath; + }))); // uniq in order to do not cache the same directories twice return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); }); /** - * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is empty + * Finds the cache directories configured for the repo ignoring cache-dependency-path * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @return list of files on which the cache depends */ -const cacheFoldersPathsForRoot = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { +const getCacheDirectoriesForRootProject = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(); core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the root directory`); return [cacheFolderPath]; }); /** - * Main function to find the cache directories configured for the repo + * A function to find the cache directories configured for the repo * currently it handles only the case of PM=yarn && cacheDependencyPath is not empty * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of files on which the cache depends */ -const getCacheDirectoriesPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - // TODO: multiple directories limited to yarn so far - return packageManagerInfo === exports.supportedPackageManagers.yarn - ? cacheDependencyPathToCacheFoldersPaths(packageManagerInfo, cacheDependencyPath) - : cacheFoldersPathsForRoot(packageManagerInfo); +const getCacheDirectories = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + // For yarn, if cacheDependencyPath is set, ask information about cache folders in each project + // folder satisfied by cacheDependencyPath https://github.com/actions/setup-node/issues/488 + if (packageManagerInfo.name === 'yarn' && cacheDependencyPath) { + return getCacheDirectoriesFromCacheDependencyPath(packageManagerInfo, cacheDependencyPath); + } + return getCacheDirectoriesForRootProject(packageManagerInfo); }); -exports.getCacheDirectoriesPaths = getCacheDirectoriesPaths; +exports.getCacheDirectories = getCacheDirectories; function isGhes() { const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; diff --git a/dist/setup/index.js b/dist/setup/index.js index 23abc1609..39a3cef8f 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71144,7 +71144,7 @@ const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, throw new Error(`Caching for '${packageManager}' is not supported`); } const platform = process.env.RUNNER_OS; - const cachePaths = yield cache_utils_1.getCacheDirectoriesPaths(packageManagerInfo, cacheDependencyPath); + const cachePaths = yield cache_utils_1.getCacheDirectories(packageManagerInfo, cacheDependencyPath); const lockFilePath = cacheDependencyPath ? cacheDependencyPath : findLockFile(packageManagerInfo); @@ -71216,38 +71216,33 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectoriesPaths = exports.expandCacheDependencyPath = exports.expandedPatternsMemoized = exports.getPackageManagerInfo = exports.getCommandOutputGuarded = exports.getCommandOutput = exports.supportedPackageManagers = exports.yarn2GetCacheFolderCommand = exports.yarn1GetCacheFolderCommand = exports.pnpmGetCacheFolderCommand = exports.npmGetCacheFolderCommand = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectories = exports.memoizedCacheDependencies = exports.getPackageManagerInfo = exports.getCommandOutputNotEmpty = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); const glob = __importStar(__nccwpck_require__(8090)); const path_1 = __importDefault(__nccwpck_require__(1017)); const fs_1 = __importDefault(__nccwpck_require__(7147)); -// for testing purposes -exports.npmGetCacheFolderCommand = 'npm config get cache'; -exports.pnpmGetCacheFolderCommand = 'pnpm store path --silent'; -exports.yarn1GetCacheFolderCommand = 'yarn cache dir'; -exports.yarn2GetCacheFolderCommand = 'yarn config get cacheFolder'; exports.supportedPackageManagers = { npm: { name: 'npm', lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], - getCacheFolderPath: () => exports.getCommandOutputGuarded(exports.npmGetCacheFolderCommand, 'Could not get npm cache folder path') + getCacheFolderPath: () => exports.getCommandOutputNotEmpty('npm config get cache', 'Could not get npm cache folder path') }, pnpm: { name: 'pnpm', lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderPath: () => exports.getCommandOutputGuarded(exports.pnpmGetCacheFolderCommand, 'Could not get pnpm cache folder path') + getCacheFolderPath: () => exports.getCommandOutputNotEmpty('pnpm store path --silent', 'Could not get pnpm cache folder path') }, yarn: { name: 'yarn', lockFilePatterns: ['yarn.lock'], getCacheFolderPath: (projectDir) => __awaiter(void 0, void 0, void 0, function* () { - const yarnVersion = yield exports.getCommandOutputGuarded(`yarn --version`, 'Could not retrieve version of yarn', projectDir); - core.debug(`Consumed yarn version is ${yarnVersion} (working dir: "${projectDir}")`); + const yarnVersion = yield exports.getCommandOutputNotEmpty(`yarn --version`, 'Could not retrieve version of yarn', projectDir); + core.debug(`Consumed yarn version is ${yarnVersion} (working dir: "${projectDir || ''}")`); const stdOut = yarnVersion.startsWith('1.') - ? yield exports.getCommandOutput(exports.yarn1GetCacheFolderCommand, projectDir) - : yield exports.getCommandOutput(exports.yarn2GetCacheFolderCommand, projectDir); + ? yield exports.getCommandOutput('yarn cache dir', projectDir) + : yield exports.getCommandOutput('yarn config get cacheFolder', projectDir); if (!stdOut) { throw new Error(`Could not get yarn cache folder path for ${projectDir}`); } @@ -71266,14 +71261,14 @@ const getCommandOutput = (toolCommand, cwd) => __awaiter(void 0, void 0, void 0, return stdout.trim(); }); exports.getCommandOutput = getCommandOutput; -const getCommandOutputGuarded = (toolCommand, error, cwd) => __awaiter(void 0, void 0, void 0, function* () { +const getCommandOutputNotEmpty = (toolCommand, error, cwd) => __awaiter(void 0, void 0, void 0, function* () { const stdOut = exports.getCommandOutput(toolCommand, cwd); if (!stdOut) { throw new Error(error); } return stdOut; }); -exports.getCommandOutputGuarded = getCommandOutputGuarded; +exports.getCommandOutputNotEmpty = getCommandOutputNotEmpty; const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { if (packageManager === 'npm') { return exports.supportedPackageManagers.npm; @@ -71293,54 +71288,7 @@ exports.getPackageManagerInfo = getPackageManagerInfo; * glob expanding memoized because it involves potentially very deep * traversing through the directories tree */ -exports.expandedPatternsMemoized = {}; -/** - * Wrapper around `glob.create(pattern).glob()` with the memoization - * @param pattern is expected to be a globed path - * @return list of files or directories expanded from glob - */ -const globPatternToArray = (pattern) => __awaiter(void 0, void 0, void 0, function* () { - const memoized = exports.expandedPatternsMemoized[pattern]; - if (memoized) - return Promise.resolve(memoized); - const globber = yield glob.create(pattern); - const expanded = yield globber.glob(); - exports.expandedPatternsMemoized[pattern] = expanded; - return expanded; -}); -/** - * Expands (converts) the string input `cache-dependency-path` to list of files' paths - * First it breaks the input by new lines and then expand glob patterns if any - * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns - * @return list of files on which the cache depends - */ -const expandCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const multilinePaths = cacheDependencyPath - .split(/\r?\n/) - .map(path => path.trim()) - .filter(path => Boolean(path)); - const expandedPathsPromises = multilinePaths.map(path => path.includes('*') ? globPatternToArray(path) : Promise.resolve([path])); - const expandedPaths = yield Promise.all(expandedPathsPromises); - return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); -}); -exports.expandCacheDependencyPath = expandCacheDependencyPath; -/** - * Converts dependency file path to the directory it resides in and ensures the directory exists - * @param cacheDependencyPath - a file name path - * @return either directory containing the file or null - */ -const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { - const projectDirectory = path_1.default.dirname(cacheDependencyPath); - if (fs_1.default.existsSync(projectDirectory) && - fs_1.default.lstatSync(projectDirectory).isDirectory()) { - core.debug(`Project directory "${projectDirectory}" derived from cache-dependency-path: "${cacheDependencyPath}"`); - return projectDirectory; - } - else { - core.debug(`No project directory found for cache-dependency-path: "${cacheDependencyPath}", will be skipped`); - return null; - } -}; +exports.memoizedCacheDependencies = {}; /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots @@ -71348,69 +71296,76 @@ const cacheDependencyPathToProjectDirectory = (cacheDependencyPath) => { * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of directories and possible */ -const cacheDependencyPathToProjectsDirectories = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const cacheDependenciesPaths = yield exports.expandCacheDependencyPath(cacheDependencyPath); +const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + let cacheDependenciesPaths; + // memoize unglobbed paths to avoid traversing FS + const memoized = exports.memoizedCacheDependencies[cacheDependencyPath]; + if (memoized) { + cacheDependenciesPaths = memoized; + } + else { + cacheDependenciesPaths = (yield glob + .create(cacheDependencyPath) + .then(globber => globber.glob())) || ['']; + exports.memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; + } const existingDirectories = cacheDependenciesPaths - .map(cacheDependencyPath => cacheDependencyPathToProjectDirectory(cacheDependencyPath)) - .filter(path => path !== null); + .map(cacheDependencyPath => path_1.default.dirname(cacheDependencyPath)) + // uniq in order to do not traverse the same directories during the further processing + .filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i) + .filter(directory => fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected // result to the whole build if (existingDirectories.length === 0) throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); - // uniq in order to do not traverse the same directories during the further processing - return existingDirectories.filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i); + return existingDirectories; }); /** - * Utility function to be used from within `map` - * Finds the cache directories configured for the project directory - * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM - * @param projectDirectory - the string pointing out to a project dir (i.e. directory with its own .yarnrc) - * @return list of directories to be cached according to the project configuration in the directory - */ -const projectDirectoryToCacheFolderPath = (packageManagerInfo, projectDirectory) => __awaiter(void 0, void 0, void 0, function* () { - const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(projectDirectory); - core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); - return cacheFolderPath; -}); -/** - * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is not empty + * Finds the cache directories configured for the repo if cache-dependency-path is not empty * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of files on which the cache depends */ -const cacheDependencyPathToCacheFoldersPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const projectDirectories = yield cacheDependencyPathToProjectsDirectories(cacheDependencyPath); - const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory))); +const getCacheDirectoriesFromCacheDependencyPath = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const projectDirectories = yield getProjectDirectoriesFromCacheDependencyPath(cacheDependencyPath); + const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => packageManagerInfo + .getCacheFolderPath(projectDirectory) + .then(cacheFolderPath => { + core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); + return cacheFolderPath; + }))); // uniq in order to do not cache the same directories twice return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); }); /** - * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is empty + * Finds the cache directories configured for the repo ignoring cache-dependency-path * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @return list of files on which the cache depends */ -const cacheFoldersPathsForRoot = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { +const getCacheDirectoriesForRootProject = (packageManagerInfo) => __awaiter(void 0, void 0, void 0, function* () { const cacheFolderPath = yield packageManagerInfo.getCacheFolderPath(); core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the root directory`); return [cacheFolderPath]; }); /** - * Main function to find the cache directories configured for the repo + * A function to find the cache directories configured for the repo * currently it handles only the case of PM=yarn && cacheDependencyPath is not empty * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of files on which the cache depends */ -const getCacheDirectoriesPaths = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - // TODO: multiple directories limited to yarn so far - return packageManagerInfo === exports.supportedPackageManagers.yarn - ? cacheDependencyPathToCacheFoldersPaths(packageManagerInfo, cacheDependencyPath) - : cacheFoldersPathsForRoot(packageManagerInfo); +const getCacheDirectories = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + // For yarn, if cacheDependencyPath is set, ask information about cache folders in each project + // folder satisfied by cacheDependencyPath https://github.com/actions/setup-node/issues/488 + if (packageManagerInfo.name === 'yarn' && cacheDependencyPath) { + return getCacheDirectoriesFromCacheDependencyPath(packageManagerInfo, cacheDependencyPath); + } + return getCacheDirectoriesForRootProject(packageManagerInfo); }); -exports.getCacheDirectoriesPaths = getCacheDirectoriesPaths; +exports.getCacheDirectories = getCacheDirectories; function isGhes() { const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; diff --git a/src/cache-restore.ts b/src/cache-restore.ts index 801d525c2..cddc41276 100644 --- a/src/cache-restore.ts +++ b/src/cache-restore.ts @@ -6,7 +6,7 @@ import fs from 'fs'; import {State} from './constants'; import { - getCacheDirectoriesPaths, + getCacheDirectories, getPackageManagerInfo, PackageManagerInfo } from './cache-utils'; @@ -21,7 +21,7 @@ export const restoreCache = async ( } const platform = process.env.RUNNER_OS; - const cachePaths = await getCacheDirectoriesPaths( + const cachePaths = await getCacheDirectories( packageManagerInfo, cacheDependencyPath ); diff --git a/src/cache-save.ts b/src/cache-save.ts index a54a741d0..6b53a904c 100644 --- a/src/cache-save.ts +++ b/src/cache-save.ts @@ -1,7 +1,7 @@ import * as core from '@actions/core'; import * as cache from '@actions/cache'; import {State} from './constants'; -import {getCacheDirectoriesPaths, getPackageManagerInfo} from './cache-utils'; +import {getCacheDirectories, getPackageManagerInfo} from './cache-utils'; // Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in // @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to @@ -33,7 +33,7 @@ const cachePackages = async (packageManager: string) => { // TODO: core.getInput has a bug - it can return undefined despite its definition (tests only?) // export declare function getInput(name: string, options?: InputOptions): string; const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; - const cachePaths = await getCacheDirectoriesPaths( + const cachePaths = await getCacheDirectories( packageManagerInfo, cacheDependencyPath ); diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 4fc69717a..2d244b65b 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -16,19 +16,13 @@ interface SupportedPackageManagers { pnpm: PackageManagerInfo; yarn: PackageManagerInfo; } - -// for testing purposes -export const npmGetCacheFolderCommand = 'npm config get cache'; -export const pnpmGetCacheFolderCommand = 'pnpm store path --silent'; -export const yarn1GetCacheFolderCommand = 'yarn cache dir'; -export const yarn2GetCacheFolderCommand = 'yarn config get cacheFolder'; export const supportedPackageManagers: SupportedPackageManagers = { npm: { name: 'npm', lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], getCacheFolderPath: () => - getCommandOutputGuarded( - npmGetCacheFolderCommand, + getCommandOutputNotEmpty( + 'npm config get cache', 'Could not get npm cache folder path' ) }, @@ -36,8 +30,8 @@ export const supportedPackageManagers: SupportedPackageManagers = { name: 'pnpm', lockFilePatterns: ['pnpm-lock.yaml'], getCacheFolderPath: () => - getCommandOutputGuarded( - pnpmGetCacheFolderCommand, + getCommandOutputNotEmpty( + 'pnpm store path --silent', 'Could not get pnpm cache folder path' ) }, @@ -45,19 +39,21 @@ export const supportedPackageManagers: SupportedPackageManagers = { name: 'yarn', lockFilePatterns: ['yarn.lock'], getCacheFolderPath: async projectDir => { - const yarnVersion = await getCommandOutputGuarded( + const yarnVersion = await getCommandOutputNotEmpty( `yarn --version`, 'Could not retrieve version of yarn', projectDir ); core.debug( - `Consumed yarn version is ${yarnVersion} (working dir: "${projectDir}")` + `Consumed yarn version is ${yarnVersion} (working dir: "${ + projectDir || '' + }")` ); const stdOut = yarnVersion.startsWith('1.') - ? await getCommandOutput(yarn1GetCacheFolderCommand, projectDir) - : await getCommandOutput(yarn2GetCacheFolderCommand, projectDir); + ? await getCommandOutput('yarn cache dir', projectDir) + : await getCommandOutput('yarn config get cacheFolder', projectDir); if (!stdOut) { throw new Error( @@ -89,7 +85,7 @@ export const getCommandOutput = async ( return stdout.trim(); }; -export const getCommandOutputGuarded = async ( +export const getCommandOutputNotEmpty = async ( toolCommand: string, error: string, cwd?: string @@ -117,66 +113,7 @@ export const getPackageManagerInfo = async (packageManager: string) => { * glob expanding memoized because it involves potentially very deep * traversing through the directories tree */ -export const expandedPatternsMemoized: Record = {}; -/** - * Wrapper around `glob.create(pattern).glob()` with the memoization - * @param pattern is expected to be a globed path - * @return list of files or directories expanded from glob - */ -const globPatternToArray = async (pattern: string): Promise => { - const memoized = expandedPatternsMemoized[pattern]; - if (memoized) return Promise.resolve(memoized); - const globber = await glob.create(pattern); - const expanded = await globber.glob(); - expandedPatternsMemoized[pattern] = expanded; - return expanded; -}; - -/** - * Expands (converts) the string input `cache-dependency-path` to list of files' paths - * First it breaks the input by new lines and then expand glob patterns if any - * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns - * @return list of files on which the cache depends - */ -export const expandCacheDependencyPath = async ( - cacheDependencyPath: string -): Promise => { - const multilinePaths = cacheDependencyPath - .split(/\r?\n/) - .map(path => path.trim()) - .filter(path => Boolean(path)); - const expandedPathsPromises: Promise[] = multilinePaths.map(path => - path.includes('*') ? globPatternToArray(path) : Promise.resolve([path]) - ); - const expandedPaths: string[][] = await Promise.all(expandedPathsPromises); - return expandedPaths.length === 0 ? [''] : expandedPaths.flat(); -}; - -/** - * Converts dependency file path to the directory it resides in and ensures the directory exists - * @param cacheDependencyPath - a file name path - * @return either directory containing the file or null - */ -const cacheDependencyPathToProjectDirectory = ( - cacheDependencyPath: string -): string | null => { - const projectDirectory = path.dirname(cacheDependencyPath); - if ( - fs.existsSync(projectDirectory) && - fs.lstatSync(projectDirectory).isDirectory() - ) { - core.debug( - `Project directory "${projectDirectory}" derived from cache-dependency-path: "${cacheDependencyPath}"` - ); - return projectDirectory; - } else { - core.debug( - `No project directory found for cache-dependency-path: "${cacheDependencyPath}", will be skipped` - ); - return null; - } -}; - +export const memoizedCacheDependencies: Record = {}; /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots @@ -184,18 +121,33 @@ const cacheDependencyPathToProjectDirectory = ( * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of directories and possible */ -const cacheDependencyPathToProjectsDirectories = async ( +const getProjectDirectoriesFromCacheDependencyPath = async ( cacheDependencyPath: string ): Promise => { - const cacheDependenciesPaths = await expandCacheDependencyPath( - cacheDependencyPath - ); + let cacheDependenciesPaths: string[]; + + // memoize unglobbed paths to avoid traversing FS + const memoized = memoizedCacheDependencies[cacheDependencyPath]; + if (memoized) { + cacheDependenciesPaths = memoized; + } else { + cacheDependenciesPaths = (await glob + .create(cacheDependencyPath) + .then(globber => globber.glob())) || ['']; + memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; + } const existingDirectories: string[] = cacheDependenciesPaths - .map(cacheDependencyPath => - cacheDependencyPathToProjectDirectory(cacheDependencyPath) + .map(cacheDependencyPath => path.dirname(cacheDependencyPath)) + // uniq in order to do not traverse the same directories during the further processing + .filter( + (cachePath, i, result) => + cachePath != null && result.indexOf(cachePath) === i ) - .filter(path => path !== null) as string[]; + .filter( + directory => + fs.existsSync(directory) && fs.lstatSync(directory).isDirectory() + ) as string[]; // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected @@ -205,50 +157,33 @@ const cacheDependencyPathToProjectsDirectories = async ( 'No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"' ); - // uniq in order to do not traverse the same directories during the further processing - return existingDirectories.filter( - (cachePath, i, result) => - cachePath != null && result.indexOf(cachePath) === i - ); -}; - -/** - * Utility function to be used from within `map` - * Finds the cache directories configured for the project directory - * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM - * @param projectDirectory - the string pointing out to a project dir (i.e. directory with its own .yarnrc) - * @return list of directories to be cached according to the project configuration in the directory - */ -const projectDirectoryToCacheFolderPath = async ( - packageManagerInfo: PackageManagerInfo, - projectDirectory: string -): Promise => { - const cacheFolderPath = await packageManagerInfo.getCacheFolderPath( - projectDirectory - ); - core.debug( - `${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"` - ); - return cacheFolderPath; + return existingDirectories; }; /** - * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is not empty + * Finds the cache directories configured for the repo if cache-dependency-path is not empty * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of files on which the cache depends */ -const cacheDependencyPathToCacheFoldersPaths = async ( +const getCacheDirectoriesFromCacheDependencyPath = async ( packageManagerInfo: PackageManagerInfo, cacheDependencyPath: string ): Promise => { - const projectDirectories = await cacheDependencyPathToProjectsDirectories( + const projectDirectories = await getProjectDirectoriesFromCacheDependencyPath( cacheDependencyPath ); const cacheFoldersPaths = await Promise.all( projectDirectories.map(projectDirectory => - projectDirectoryToCacheFolderPath(packageManagerInfo, projectDirectory) + packageManagerInfo + .getCacheFolderPath(projectDirectory) + .then(cacheFolderPath => { + core.debug( + `${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"` + ); + return cacheFolderPath; + }) ) ); // uniq in order to do not cache the same directories twice @@ -258,11 +193,11 @@ const cacheDependencyPathToCacheFoldersPaths = async ( }; /** - * Top-entry function to find the cache directories configured for the repo if cache-dependency-path is empty + * Finds the cache directories configured for the repo ignoring cache-dependency-path * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @return list of files on which the cache depends */ -const cacheFoldersPathsForRoot = async ( +const getCacheDirectoriesForRootProject = async ( packageManagerInfo: PackageManagerInfo ): Promise => { const cacheFolderPath = await packageManagerInfo.getCacheFolderPath(); @@ -273,24 +208,27 @@ const cacheFoldersPathsForRoot = async ( }; /** - * Main function to find the cache directories configured for the repo + * A function to find the cache directories configured for the repo * currently it handles only the case of PM=yarn && cacheDependencyPath is not empty * @param packageManagerInfo - an object having getCacheFolderPath method specific to given PM * @param cacheDependencyPath - either a single string or multiline string with possible glob patterns * expected to be the result of `core.getInput('cache-dependency-path')` * @return list of files on which the cache depends */ -export const getCacheDirectoriesPaths = async ( +export const getCacheDirectories = async ( packageManagerInfo: PackageManagerInfo, cacheDependencyPath: string -): Promise => - // TODO: multiple directories limited to yarn so far - packageManagerInfo === supportedPackageManagers.yarn - ? cacheDependencyPathToCacheFoldersPaths( - packageManagerInfo, - cacheDependencyPath - ) - : cacheFoldersPathsForRoot(packageManagerInfo); +): Promise => { + // For yarn, if cacheDependencyPath is set, ask information about cache folders in each project + // folder satisfied by cacheDependencyPath https://github.com/actions/setup-node/issues/488 + if (packageManagerInfo.name === 'yarn' && cacheDependencyPath) { + return getCacheDirectoriesFromCacheDependencyPath( + packageManagerInfo, + cacheDependencyPath + ); + } + return getCacheDirectoriesForRootProject(packageManagerInfo); +}; export function isGhes(): boolean { const ghUrl = new URL( From d2b7e08b805651040ed23e4f7f3ba8d8dd6da1b3 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Fri, 2 Jun 2023 18:50:25 +0200 Subject: [PATCH 15/21] review fixes --- dist/cache-save/index.js | 11 +++++------ dist/setup/index.js | 11 +++++------ src/cache-utils.ts | 16 +++++----------- 3 files changed, 15 insertions(+), 23 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index b7b72fdec..5baad46c0 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -60522,15 +60522,14 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ cacheDependenciesPaths = memoized; } else { - cacheDependenciesPaths = (yield glob - .create(cacheDependencyPath) - .then(globber => globber.glob())) || ['']; + const globber = yield glob.create(cacheDependencyPath); + cacheDependenciesPaths = (yield globber.glob()) || ['']; exports.memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; } const existingDirectories = cacheDependenciesPaths - .map(cacheDependencyPath => path_1.default.dirname(cacheDependencyPath)) + .map(path_1.default.dirname) // uniq in order to do not traverse the same directories during the further processing - .filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i) + .filter((item, i, src) => item != null && src.indexOf(item) === i) .filter(directory => fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected @@ -60555,7 +60554,7 @@ const getCacheDirectoriesFromCacheDependencyPath = (packageManagerInfo, cacheDep return cacheFolderPath; }))); // uniq in order to do not cache the same directories twice - return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); + return cacheFoldersPaths.filter((item, i, src) => src.indexOf(item) === i); }); /** * Finds the cache directories configured for the repo ignoring cache-dependency-path diff --git a/dist/setup/index.js b/dist/setup/index.js index 39a3cef8f..6b2f7404d 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71304,15 +71304,14 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ cacheDependenciesPaths = memoized; } else { - cacheDependenciesPaths = (yield glob - .create(cacheDependencyPath) - .then(globber => globber.glob())) || ['']; + const globber = yield glob.create(cacheDependencyPath); + cacheDependenciesPaths = (yield globber.glob()) || ['']; exports.memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; } const existingDirectories = cacheDependenciesPaths - .map(cacheDependencyPath => path_1.default.dirname(cacheDependencyPath)) + .map(path_1.default.dirname) // uniq in order to do not traverse the same directories during the further processing - .filter((cachePath, i, result) => cachePath != null && result.indexOf(cachePath) === i) + .filter((item, i, src) => item != null && src.indexOf(item) === i) .filter(directory => fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected @@ -71337,7 +71336,7 @@ const getCacheDirectoriesFromCacheDependencyPath = (packageManagerInfo, cacheDep return cacheFolderPath; }))); // uniq in order to do not cache the same directories twice - return cacheFoldersPaths.filter((cachePath, i, result) => result.indexOf(cachePath) === i); + return cacheFoldersPaths.filter((item, i, src) => src.indexOf(item) === i); }); /** * Finds the cache directories configured for the repo ignoring cache-dependency-path diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 2d244b65b..5884c000c 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -131,19 +131,15 @@ const getProjectDirectoriesFromCacheDependencyPath = async ( if (memoized) { cacheDependenciesPaths = memoized; } else { - cacheDependenciesPaths = (await glob - .create(cacheDependencyPath) - .then(globber => globber.glob())) || ['']; + const globber = await glob.create(cacheDependencyPath); + cacheDependenciesPaths = (await globber.glob()) || ['']; memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; } const existingDirectories: string[] = cacheDependenciesPaths - .map(cacheDependencyPath => path.dirname(cacheDependencyPath)) + .map(path.dirname) // uniq in order to do not traverse the same directories during the further processing - .filter( - (cachePath, i, result) => - cachePath != null && result.indexOf(cachePath) === i - ) + .filter((item, i, src) => item != null && src.indexOf(item) === i) .filter( directory => fs.existsSync(directory) && fs.lstatSync(directory).isDirectory() @@ -187,9 +183,7 @@ const getCacheDirectoriesFromCacheDependencyPath = async ( ) ); // uniq in order to do not cache the same directories twice - return cacheFoldersPaths.filter( - (cachePath, i, result) => result.indexOf(cachePath) === i - ); + return cacheFoldersPaths.filter((item, i, src) => src.indexOf(item) === i); }; /** From 885f6b5c3615c8d45b60b1880b3f085879379567 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Mon, 5 Jun 2023 17:55:29 +0200 Subject: [PATCH 16/21] add e2e --- .github/workflows/yarn-subprojects.yml | 81 ++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 .github/workflows/yarn-subprojects.yml diff --git a/.github/workflows/yarn-subprojects.yml b/.github/workflows/yarn-subprojects.yml new file mode 100644 index 000000000..4bdd44d4d --- /dev/null +++ b/.github/workflows/yarn-subprojects.yml @@ -0,0 +1,81 @@ +# This is a basic workflow to help you get started with Actions + +name: CI + +on: + push: + + workflow_dispatch: + +jobs: + build: + strategy: + matrix: + node-version: [16] + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: prepare sub-projects + env: + YARN_ENABLE_IMMUTABLE_INSTALLS: false + run: | + echo "create yarn2 project in the sub2" + mkdir sub2 + cd sub2 + cat <package.json + { + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } + } + EOT + yarn set version 2.4.3 + yarn install + + echo "create yarn3 project in the sub3" + cd .. + mkdir sub3 + cd sub3 + cat <package.json + { + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } + } + EOT + yarn set version 3.5.1 + yarn install + + echo "create yarn1 project in the root" + cd .. + cat <package.json + { + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } + } + EOT + yarn set version 1.22.19 + yarn install + + # expect + # - no errors + # - log + # ##[debug]Cache Paths: + # ##[debug]["sub2/.yarn/cache","sub3/.yarn/cache","../../../.cache/yarn/v6"] + - name: Setup Node + uses: ./ + with: + node-version: ${{ matrix.node-version }} + cache: 'yarn' + cache-dependency-path: | + **/*.lock + yarn.lock From b8b9502971ef64f28779f8a792f8af328bbc13e8 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Tue, 6 Jun 2023 15:01:39 +0200 Subject: [PATCH 17/21] Add unique --- dist/cache-save/index.js | 120 +++++++++++++++++++++++++++++++++++++-- dist/setup/index.js | 22 +++++-- src/cache-utils.ts | 13 ++--- src/util.ts | 9 +++ 4 files changed, 148 insertions(+), 16 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 5baad46c0..da0215cc1 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -60441,6 +60441,7 @@ const cache = __importStar(__nccwpck_require__(7799)); const glob = __importStar(__nccwpck_require__(8090)); const path_1 = __importDefault(__nccwpck_require__(1017)); const fs_1 = __importDefault(__nccwpck_require__(7147)); +const util_1 = __nccwpck_require__(2629); exports.supportedPackageManagers = { npm: { name: 'npm', @@ -60528,9 +60529,10 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ } const existingDirectories = cacheDependenciesPaths .map(path_1.default.dirname) - // uniq in order to do not traverse the same directories during the further processing - .filter((item, i, src) => item != null && src.indexOf(item) === i) - .filter(directory => fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isDirectory()); + .filter(path => path != null) + .filter(util_1.unique()) + .filter(fs_1.default.existsSync) + .filter(directory => fs_1.default.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected // result to the whole build @@ -60554,7 +60556,7 @@ const getCacheDirectoriesFromCacheDependencyPath = (packageManagerInfo, cacheDep return cacheFolderPath; }))); // uniq in order to do not cache the same directories twice - return cacheFoldersPaths.filter((item, i, src) => src.indexOf(item) === i); + return cacheFoldersPaths.filter(util_1.unique()); }); /** * Finds the cache directories configured for the repo ignoring cache-dependency-path @@ -60627,6 +60629,116 @@ var Outputs; })(Outputs = exports.Outputs || (exports.Outputs = {})); +/***/ }), + +/***/ 2629: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.unique = exports.printEnvDetailsAndSetOutput = exports.parseNodeVersionFile = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +function parseNodeVersionFile(contents) { + var _a, _b, _c; + let nodeVersion; + // Try parsing the file as an NPM `package.json` file. + try { + nodeVersion = (_a = JSON.parse(contents).volta) === null || _a === void 0 ? void 0 : _a.node; + if (!nodeVersion) + nodeVersion = (_b = JSON.parse(contents).engines) === null || _b === void 0 ? void 0 : _b.node; + } + catch (_d) { + core.info('Node version file is not JSON file'); + } + if (!nodeVersion) { + const found = contents.match(/^(?:nodejs\s+)?v?(?[^\s]+)$/m); + nodeVersion = (_c = found === null || found === void 0 ? void 0 : found.groups) === null || _c === void 0 ? void 0 : _c.version; + } + // In the case of an unknown format, + // return as is and evaluate the version separately. + if (!nodeVersion) + nodeVersion = contents.trim(); + return nodeVersion; +} +exports.parseNodeVersionFile = parseNodeVersionFile; +function printEnvDetailsAndSetOutput() { + return __awaiter(this, void 0, void 0, function* () { + core.startGroup('Environment details'); + const promises = ['node', 'npm', 'yarn'].map((tool) => __awaiter(this, void 0, void 0, function* () { + const output = yield getToolVersion(tool, ['--version']); + return { tool, output }; + })); + const tools = yield Promise.all(promises); + tools.forEach(({ tool, output }) => { + if (tool === 'node') { + core.setOutput(`${tool}-version`, output); + } + core.info(`${tool}: ${output}`); + }); + core.endGroup(); + }); +} +exports.printEnvDetailsAndSetOutput = printEnvDetailsAndSetOutput; +function getToolVersion(tool, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + const { stdout, stderr, exitCode } = yield exec.getExecOutput(tool, options, { + ignoreReturnCode: true, + silent: true + }); + if (exitCode > 0) { + core.info(`[warning]${stderr}`); + return ''; + } + return stdout.trim(); + } + catch (err) { + return ''; + } + }); +} +const unique = () => { + const encountered = new Set(); + return (value) => { + if (encountered.has(value)) + return false; + encountered.add(value); + return true; + }; +}; +exports.unique = unique; + + /***/ }), /***/ 2877: diff --git a/dist/setup/index.js b/dist/setup/index.js index 6b2f7404d..ab004fe01 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71223,6 +71223,7 @@ const cache = __importStar(__nccwpck_require__(7799)); const glob = __importStar(__nccwpck_require__(8090)); const path_1 = __importDefault(__nccwpck_require__(1017)); const fs_1 = __importDefault(__nccwpck_require__(7147)); +const util_1 = __nccwpck_require__(2629); exports.supportedPackageManagers = { npm: { name: 'npm', @@ -71310,9 +71311,10 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ } const existingDirectories = cacheDependenciesPaths .map(path_1.default.dirname) - // uniq in order to do not traverse the same directories during the further processing - .filter((item, i, src) => item != null && src.indexOf(item) === i) - .filter(directory => fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isDirectory()); + .filter(path => path != null) + .filter(util_1.unique()) + .filter(fs_1.default.existsSync) + .filter(directory => fs_1.default.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected // result to the whole build @@ -71336,7 +71338,7 @@ const getCacheDirectoriesFromCacheDependencyPath = (packageManagerInfo, cacheDep return cacheFolderPath; }))); // uniq in order to do not cache the same directories twice - return cacheFoldersPaths.filter((item, i, src) => src.indexOf(item) === i); + return cacheFoldersPaths.filter(util_1.unique()); }); /** * Finds the cache directories configured for the repo ignoring cache-dependency-path @@ -72240,7 +72242,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.printEnvDetailsAndSetOutput = exports.parseNodeVersionFile = void 0; +exports.unique = exports.printEnvDetailsAndSetOutput = exports.parseNodeVersionFile = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); function parseNodeVersionFile(contents) { @@ -72302,6 +72304,16 @@ function getToolVersion(tool, options) { } }); } +const unique = () => { + const encountered = new Set(); + return (value) => { + if (encountered.has(value)) + return false; + encountered.add(value); + return true; + }; +}; +exports.unique = unique; /***/ }), diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 5884c000c..484ea3be6 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -4,6 +4,7 @@ import * as cache from '@actions/cache'; import * as glob from '@actions/glob'; import path from 'path'; import fs from 'fs'; +import {unique} from './util'; export interface PackageManagerInfo { name: string; @@ -138,12 +139,10 @@ const getProjectDirectoriesFromCacheDependencyPath = async ( const existingDirectories: string[] = cacheDependenciesPaths .map(path.dirname) - // uniq in order to do not traverse the same directories during the further processing - .filter((item, i, src) => item != null && src.indexOf(item) === i) - .filter( - directory => - fs.existsSync(directory) && fs.lstatSync(directory).isDirectory() - ) as string[]; + .filter(path => path != null) + .filter(unique()) + .filter(fs.existsSync) + .filter(directory => fs.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected @@ -183,7 +182,7 @@ const getCacheDirectoriesFromCacheDependencyPath = async ( ) ); // uniq in order to do not cache the same directories twice - return cacheFoldersPaths.filter((item, i, src) => src.indexOf(item) === i); + return cacheFoldersPaths.filter(unique()); }; /** diff --git a/src/util.ts b/src/util.ts index 60f2649c2..39e482456 100644 --- a/src/util.ts +++ b/src/util.ts @@ -61,3 +61,12 @@ async function getToolVersion(tool: string, options: string[]) { return ''; } } + +export const unique = () => { + const encountered = new Set(); + return (value: unknown): boolean => { + if (encountered.has(value)) return false; + encountered.add(value); + return true; + }; +}; From 6aacde798c0bef17939ebc8d13f33f917c81aa82 Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Thu, 8 Jun 2023 13:44:41 +0200 Subject: [PATCH 18/21] review updates --- .github/workflows/e2e-cache.yml | 75 ++++++++ .github/workflows/yarn-subprojects.yml | 81 --------- __tests__/cache-save.test.ts | 239 ++++++++++++------------- dist/cache-save/index.js | 19 +- dist/setup/index.js | 12 +- src/cache-restore.ts | 1 + src/cache-save.ts | 14 +- src/cache-utils.ts | 23 ++- src/constants.ts | 3 +- 9 files changed, 222 insertions(+), 245 deletions(-) delete mode 100644 .github/workflows/yarn-subprojects.yml diff --git a/.github/workflows/e2e-cache.yml b/.github/workflows/e2e-cache.yml index fab3dcd74..0d0da14c7 100644 --- a/.github/workflows/e2e-cache.yml +++ b/.github/workflows/e2e-cache.yml @@ -134,3 +134,78 @@ jobs: - name: Verify node and yarn run: __tests__/verify-node.sh "${{ matrix.node-version }}" shell: bash + + yarn-subprojects: + name: Test yarn subprojects + strategy: + matrix: + node-version: [12, 14, 16] + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: prepare sub-projects + env: + YARN_ENABLE_IMMUTABLE_INSTALLS: false + run: | + rm package.json + rm package-lock.json + echo "create yarn2 project in the sub2" + mkdir sub2 + cd sub2 + cat <package.json + { + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } + } + EOT + yarn set version 2.4.3 + yarn install + + echo "create yarn3 project in the sub3" + cd .. + mkdir sub3 + cd sub3 + cat <package.json + { + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } + } + EOT + yarn set version 3.5.1 + yarn install + + echo "create yarn1 project in the root" + cd .. + cat <package.json + { + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } + } + EOT + yarn set version 1.22.19 + yarn install + + # expect + # - no errors + # - log + # ##[debug]Cache Paths: + # ##[debug]["sub2/.yarn/cache","sub3/.yarn/cache","../../../.cache/yarn/v6"] + - name: Setup Node + uses: ./ + with: + node-version: ${{ matrix.node-version }} + cache: 'yarn' + cache-dependency-path: | + **/*.lock + yarn.lock diff --git a/.github/workflows/yarn-subprojects.yml b/.github/workflows/yarn-subprojects.yml deleted file mode 100644 index 4bdd44d4d..000000000 --- a/.github/workflows/yarn-subprojects.yml +++ /dev/null @@ -1,81 +0,0 @@ -# This is a basic workflow to help you get started with Actions - -name: CI - -on: - push: - - workflow_dispatch: - -jobs: - build: - strategy: - matrix: - node-version: [16] - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: prepare sub-projects - env: - YARN_ENABLE_IMMUTABLE_INSTALLS: false - run: | - echo "create yarn2 project in the sub2" - mkdir sub2 - cd sub2 - cat <package.json - { - "name": "subproject", - "dependencies": { - "random": "^3.0.6", - "uuid": "^9.0.0" - } - } - EOT - yarn set version 2.4.3 - yarn install - - echo "create yarn3 project in the sub3" - cd .. - mkdir sub3 - cd sub3 - cat <package.json - { - "name": "subproject", - "dependencies": { - "random": "^3.0.6", - "uuid": "^9.0.0" - } - } - EOT - yarn set version 3.5.1 - yarn install - - echo "create yarn1 project in the root" - cd .. - cat <package.json - { - "name": "subproject", - "dependencies": { - "random": "^3.0.6", - "uuid": "^9.0.0" - } - } - EOT - yarn set version 1.22.19 - yarn install - - # expect - # - no errors - # - log - # ##[debug]Cache Paths: - # ##[debug]["sub2/.yarn/cache","sub3/.yarn/cache","../../../.cache/yarn/v6"] - - name: Setup Node - uses: ./ - with: - node-version: ${{ matrix.node-version }} - cache: 'yarn' - cache-dependency-path: | - **/*.lock - yarn.lock diff --git a/__tests__/cache-save.test.ts b/__tests__/cache-save.test.ts index c84621c53..a989d2b11 100644 --- a/__tests__/cache-save.test.ts +++ b/__tests__/cache-save.test.ts @@ -107,22 +107,20 @@ describe('run', () => { describe('Validate unchanged cache is not saved', () => { it('should not save cache for yarn1', async () => { inputs['cache'] = 'yarn'; - getStateSpy.mockImplementation(() => yarnFileHash); - getCommandOutputSpy - .mockImplementationOnce(() => '1.2.3') - .mockImplementationOnce(() => `${commonPath}/yarn1`); + getStateSpy.mockImplementation(key => + key === State.CachePrimaryKey || key === State.CacheMatchedKey + ? yarnFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); - expect(debugSpy).toHaveBeenCalledWith( - 'Consumed yarn version is 1.2.3 (working dir: "")' - ); - expect(debugSpy).toHaveBeenCalledWith( - 'yarn\'s cache folder "/some/random/path/yarn1" configured for the root directory' - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); @@ -131,22 +129,28 @@ describe('run', () => { it('should not save cache for yarn2', async () => { inputs['cache'] = 'yarn'; - getStateSpy.mockImplementation(() => yarnFileHash); - getCommandOutputSpy - .mockImplementationOnce(() => '2.2.3') - .mockImplementationOnce(() => `${commonPath}/yarn2`); + getStateSpy.mockImplementation(key => + key === State.CachePrimaryKey || key === State.CacheMatchedKey + ? yarnFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); + /* expect(debugSpy).toHaveBeenCalledWith( 'Consumed yarn version is 2.2.3 (working dir: "")' ); expect(debugSpy).toHaveBeenCalledWith( 'yarn\'s cache folder "/some/random/path/yarn2" configured for the root directory' ); + */ expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); @@ -155,39 +159,40 @@ describe('run', () => { it('should not save cache for npm', async () => { inputs['cache'] = 'npm'; - getStateSpy.mockImplementation(() => npmFileHash); + getStateSpy.mockImplementation(key => + key === State.CachePrimaryKey || key === State.CacheMatchedKey + ? yarnFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); getCommandOutputSpy.mockImplementationOnce(() => `${commonPath}/npm`); await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith( - `npm's cache folder "${commonPath}/npm" configured for the root directory` - ); - expect(infoSpy).toHaveBeenCalledWith( - `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(setFailedSpy).not.toHaveBeenCalled(); }); it('should not save cache for pnpm', async () => { inputs['cache'] = 'pnpm'; - getStateSpy.mockImplementation(() => pnpmFileHash); - getCommandOutputSpy.mockImplementationOnce(() => `${commonPath}/pnpm`); + getStateSpy.mockImplementation(key => + key === State.CachePrimaryKey || key === State.CacheMatchedKey + ? yarnFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith( - `pnpm's cache folder "${commonPath}/pnpm" configured for the root directory` - ); - expect(infoSpy).toHaveBeenCalledWith( - `Cache hit occurred on the primary key ${pnpmFileHash}, not saving cache.` - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(setFailedSpy).not.toHaveBeenCalled(); }); }); @@ -195,28 +200,22 @@ describe('run', () => { describe('action saves the cache', () => { it('saves cache from yarn 1', async () => { inputs['cache'] = 'yarn'; - getStateSpy.mockImplementation((name: string) => { - if (name === State.CacheMatchedKey) { - return yarnFileHash; - } else { - return npmFileHash; - } - }); - getCommandOutputSpy - .mockImplementationOnce(() => '1.2.3') - .mockImplementationOnce(() => `${commonPath}/yarn1`); + getStateSpy.mockImplementation((key: string) => + key === State.CacheMatchedKey + ? yarnFileHash + : key === State.CachePrimaryKey + ? npmFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); - expect(debugSpy).toHaveBeenCalledWith( - 'Consumed yarn version is 1.2.3 (working dir: "")' - ); - expect(debugSpy).toHaveBeenCalledWith( - 'yarn\'s cache folder "/some/random/path/yarn1" configured for the root directory' - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); @@ -229,28 +228,22 @@ describe('run', () => { it('saves cache from yarn 2', async () => { inputs['cache'] = 'yarn'; - getStateSpy.mockImplementation((name: string) => { - if (name === State.CacheMatchedKey) { - return yarnFileHash; - } else { - return npmFileHash; - } - }); - getCommandOutputSpy - .mockImplementationOnce(() => '2.2.3') - .mockImplementationOnce(() => `${commonPath}/yarn2`); + getStateSpy.mockImplementation((key: string) => + key === State.CacheMatchedKey + ? yarnFileHash + : key === State.CachePrimaryKey + ? npmFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(2); - expect(debugSpy).toHaveBeenCalledWith( - 'Consumed yarn version is 2.2.3 (working dir: "")' - ); - expect(debugSpy).toHaveBeenCalledWith( - 'yarn\'s cache folder "/some/random/path/yarn2" configured for the root directory' - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); @@ -263,23 +256,22 @@ describe('run', () => { it('saves cache from npm', async () => { inputs['cache'] = 'npm'; - getStateSpy.mockImplementation((name: string) => { - if (name === State.CacheMatchedKey) { - return npmFileHash; - } else { - return yarnFileHash; - } - }); - getCommandOutputSpy.mockImplementationOnce(() => `${commonPath}/npm`); + getStateSpy.mockImplementation((key: string) => + key === State.CacheMatchedKey + ? npmFileHash + : key === State.CachePrimaryKey + ? yarnFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith( - `npm's cache folder "${commonPath}/npm" configured for the root directory` - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` ); @@ -292,23 +284,22 @@ describe('run', () => { it('saves cache from pnpm', async () => { inputs['cache'] = 'pnpm'; - getStateSpy.mockImplementation((name: string) => { - if (name === State.CacheMatchedKey) { - return pnpmFileHash; - } else { - return npmFileHash; - } - }); - getCommandOutputSpy.mockImplementationOnce(() => `${commonPath}/pnpm`); + getStateSpy.mockImplementation((key: string) => + key === State.CacheMatchedKey + ? pnpmFileHash + : key === State.CachePrimaryKey + ? npmFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith( - `pnpm's cache folder "${commonPath}/pnpm" configured for the root directory` - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${pnpmFileHash}, not saving cache.` ); @@ -321,14 +312,15 @@ describe('run', () => { it('save with -1 cacheId , should not fail workflow', async () => { inputs['cache'] = 'npm'; - getStateSpy.mockImplementation((name: string) => { - if (name === State.CacheMatchedKey) { - return npmFileHash; - } else { - return yarnFileHash; - } - }); - getCommandOutputSpy.mockImplementationOnce(() => `${commonPath}/npm`); + getStateSpy.mockImplementation((key: string) => + key === State.CacheMatchedKey + ? npmFileHash + : key === State.CachePrimaryKey + ? yarnFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); saveCacheSpy.mockImplementation(() => { return -1; }); @@ -336,11 +328,9 @@ describe('run', () => { await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith( - `npm's cache folder "${commonPath}/npm" configured for the root directory` - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` ); @@ -353,14 +343,15 @@ describe('run', () => { it('saves with error from toolkit, should fail workflow', async () => { inputs['cache'] = 'npm'; - getStateSpy.mockImplementation((name: string) => { - if (name === State.CacheMatchedKey) { - return npmFileHash; - } else { - return yarnFileHash; - } - }); - getCommandOutputSpy.mockImplementationOnce(() => `${commonPath}/npm`); + getStateSpy.mockImplementation((key: string) => + key === State.CacheMatchedKey + ? npmFileHash + : key === State.CachePrimaryKey + ? yarnFileHash + : key === State.CachePaths + ? '["/foo/bar"]' + : 'not expected' + ); saveCacheSpy.mockImplementation(() => { throw new cache.ValidationError('Validation failed'); }); @@ -368,11 +359,9 @@ describe('run', () => { await run(); expect(getInputSpy).toHaveBeenCalled(); - expect(getStateSpy).toHaveBeenCalledTimes(2); - expect(getCommandOutputSpy).toHaveBeenCalledTimes(1); - expect(debugSpy).toHaveBeenCalledWith( - `npm's cache folder "${commonPath}/npm" configured for the root directory` - ); + expect(getStateSpy).toHaveBeenCalledTimes(3); + expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); + expect(debugSpy).toHaveBeenCalledTimes(0); expect(infoSpy).not.toHaveBeenCalledWith( `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` ); diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index da0215cc1..2b16ee16b 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -60370,16 +60370,16 @@ exports.run = run; const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { const state = core.getState(constants_1.State.CacheMatchedKey); const primaryKey = core.getState(constants_1.State.CachePrimaryKey); + const cachePaths = JSON.parse(core.getState(constants_1.State.CachePaths) || '[]'); const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); if (!packageManagerInfo) { core.debug(`Caching for '${packageManager}' is not supported`); return; } - // TODO: core.getInput has a bug - it can return undefined despite its definition (tests only?) - // export declare function getInput(name: string, options?: InputOptions): string; - const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; - const cachePaths = yield cache_utils_1.getCacheDirectories(packageManagerInfo, cacheDependencyPath); if (cachePaths.length === 0) { + // TODO: core.getInput has a bug - it can return undefined despite its definition (tests only?) + // export declare function getInput(name: string, options?: InputOptions): string; + const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; throw new Error(`Cache folder paths are not retrieved for ${packageManager} with cache-dependency-path = ${cacheDependencyPath}`); } if (primaryKey === state) { @@ -60524,19 +60524,18 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ } else { const globber = yield glob.create(cacheDependencyPath); - cacheDependenciesPaths = (yield globber.glob()) || ['']; + cacheDependenciesPaths = yield globber.glob(); exports.memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; } const existingDirectories = cacheDependenciesPaths .map(path_1.default.dirname) - .filter(path => path != null) .filter(util_1.unique()) .filter(fs_1.default.existsSync) .filter(directory => fs_1.default.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected // result to the whole build - if (existingDirectories.length === 0) + if (!existingDirectories.length) throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); return existingDirectories; }); @@ -60549,9 +60548,8 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ */ const getCacheDirectoriesFromCacheDependencyPath = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { const projectDirectories = yield getProjectDirectoriesFromCacheDependencyPath(cacheDependencyPath); - const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => packageManagerInfo - .getCacheFolderPath(projectDirectory) - .then(cacheFolderPath => { + const cacheFoldersPaths = yield Promise.all(projectDirectories.map((projectDirectory) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFolderPath = packageManagerInfo.getCacheFolderPath(projectDirectory); core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); return cacheFolderPath; }))); @@ -60622,6 +60620,7 @@ var State; (function (State) { State["CachePrimaryKey"] = "CACHE_KEY"; State["CacheMatchedKey"] = "CACHE_RESULT"; + State["CachePaths"] = "CACHE_PATHS"; })(State = exports.State || (exports.State = {})); var Outputs; (function (Outputs) { diff --git a/dist/setup/index.js b/dist/setup/index.js index ab004fe01..24865a81d 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71145,6 +71145,7 @@ const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, } const platform = process.env.RUNNER_OS; const cachePaths = yield cache_utils_1.getCacheDirectories(packageManagerInfo, cacheDependencyPath); + core.saveState(constants_1.State.CachePaths, cachePaths); const lockFilePath = cacheDependencyPath ? cacheDependencyPath : findLockFile(packageManagerInfo); @@ -71306,19 +71307,18 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ } else { const globber = yield glob.create(cacheDependencyPath); - cacheDependenciesPaths = (yield globber.glob()) || ['']; + cacheDependenciesPaths = yield globber.glob(); exports.memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; } const existingDirectories = cacheDependenciesPaths .map(path_1.default.dirname) - .filter(path => path != null) .filter(util_1.unique()) .filter(fs_1.default.existsSync) .filter(directory => fs_1.default.lstatSync(directory).isDirectory()); // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected // result to the whole build - if (existingDirectories.length === 0) + if (!existingDirectories.length) throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); return existingDirectories; }); @@ -71331,9 +71331,8 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ */ const getCacheDirectoriesFromCacheDependencyPath = (packageManagerInfo, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { const projectDirectories = yield getProjectDirectoriesFromCacheDependencyPath(cacheDependencyPath); - const cacheFoldersPaths = yield Promise.all(projectDirectories.map(projectDirectory => packageManagerInfo - .getCacheFolderPath(projectDirectory) - .then(cacheFolderPath => { + const cacheFoldersPaths = yield Promise.all(projectDirectories.map((projectDirectory) => __awaiter(void 0, void 0, void 0, function* () { + const cacheFolderPath = packageManagerInfo.getCacheFolderPath(projectDirectory); core.debug(`${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"`); return cacheFolderPath; }))); @@ -71404,6 +71403,7 @@ var State; (function (State) { State["CachePrimaryKey"] = "CACHE_KEY"; State["CacheMatchedKey"] = "CACHE_RESULT"; + State["CachePaths"] = "CACHE_PATHS"; })(State = exports.State || (exports.State = {})); var Outputs; (function (Outputs) { diff --git a/src/cache-restore.ts b/src/cache-restore.ts index cddc41276..e138707c2 100644 --- a/src/cache-restore.ts +++ b/src/cache-restore.ts @@ -25,6 +25,7 @@ export const restoreCache = async ( packageManagerInfo, cacheDependencyPath ); + core.saveState(State.CachePaths, cachePaths); const lockFilePath = cacheDependencyPath ? cacheDependencyPath : findLockFile(packageManagerInfo); diff --git a/src/cache-save.ts b/src/cache-save.ts index 6b53a904c..96f6a7d47 100644 --- a/src/cache-save.ts +++ b/src/cache-save.ts @@ -1,7 +1,7 @@ import * as core from '@actions/core'; import * as cache from '@actions/cache'; import {State} from './constants'; -import {getCacheDirectories, getPackageManagerInfo} from './cache-utils'; +import {getPackageManagerInfo} from './cache-utils'; // Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in // @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to @@ -23,6 +23,7 @@ export async function run() { const cachePackages = async (packageManager: string) => { const state = core.getState(State.CacheMatchedKey); const primaryKey = core.getState(State.CachePrimaryKey); + const cachePaths = JSON.parse(core.getState(State.CachePaths) || '[]'); const packageManagerInfo = await getPackageManagerInfo(packageManager); if (!packageManagerInfo) { @@ -30,15 +31,10 @@ const cachePackages = async (packageManager: string) => { return; } - // TODO: core.getInput has a bug - it can return undefined despite its definition (tests only?) - // export declare function getInput(name: string, options?: InputOptions): string; - const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; - const cachePaths = await getCacheDirectories( - packageManagerInfo, - cacheDependencyPath - ); - if (cachePaths.length === 0) { + // TODO: core.getInput has a bug - it can return undefined despite its definition (tests only?) + // export declare function getInput(name: string, options?: InputOptions): string; + const cacheDependencyPath = core.getInput('cache-dependency-path') || ''; throw new Error( `Cache folder paths are not retrieved for ${packageManager} with cache-dependency-path = ${cacheDependencyPath}` ); diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 484ea3be6..c30e65025 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -133,13 +133,12 @@ const getProjectDirectoriesFromCacheDependencyPath = async ( cacheDependenciesPaths = memoized; } else { const globber = await glob.create(cacheDependencyPath); - cacheDependenciesPaths = (await globber.glob()) || ['']; + cacheDependenciesPaths = await globber.glob(); memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; } const existingDirectories: string[] = cacheDependenciesPaths .map(path.dirname) - .filter(path => path != null) .filter(unique()) .filter(fs.existsSync) .filter(directory => fs.lstatSync(directory).isDirectory()); @@ -147,7 +146,7 @@ const getProjectDirectoriesFromCacheDependencyPath = async ( // if user explicitly pointed out some file, but it does not exist it is definitely // not he wanted, thus we should throw an error not trying to workaround with unexpected // result to the whole build - if (existingDirectories.length === 0) + if (!existingDirectories.length) throw Error( 'No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"' ); @@ -170,16 +169,14 @@ const getCacheDirectoriesFromCacheDependencyPath = async ( cacheDependencyPath ); const cacheFoldersPaths = await Promise.all( - projectDirectories.map(projectDirectory => - packageManagerInfo - .getCacheFolderPath(projectDirectory) - .then(cacheFolderPath => { - core.debug( - `${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"` - ); - return cacheFolderPath; - }) - ) + projectDirectories.map(async projectDirectory => { + const cacheFolderPath = + packageManagerInfo.getCacheFolderPath(projectDirectory); + core.debug( + `${packageManagerInfo.name}'s cache folder "${cacheFolderPath}" configured for the directory "${projectDirectory}"` + ); + return cacheFolderPath; + }) ); // uniq in order to do not cache the same directories twice return cacheFoldersPaths.filter(unique()); diff --git a/src/constants.ts b/src/constants.ts index 021418c2a..cd017266f 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -6,7 +6,8 @@ export enum LockType { export enum State { CachePrimaryKey = 'CACHE_KEY', - CacheMatchedKey = 'CACHE_RESULT' + CacheMatchedKey = 'CACHE_RESULT', + CachePaths = 'CACHE_PATHS' } export enum Outputs { From 3ef527264ac68164b301e0b46fb15d0472df423a Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Wed, 14 Jun 2023 19:42:28 +0200 Subject: [PATCH 19/21] review updates second stage --- __tests__/cache-restore.test.ts | 2 +- __tests__/cache-utils.test.ts | 27 ++++++++++----------------- dist/cache-save/index.js | 25 ++++--------------------- dist/setup/index.js | 27 +++++---------------------- src/cache-restore.ts | 2 +- src/cache-utils.ts | 25 ++++--------------------- 6 files changed, 25 insertions(+), 83 deletions(-) diff --git a/__tests__/cache-restore.test.ts b/__tests__/cache-restore.test.ts index 86dff3f32..90153a403 100644 --- a/__tests__/cache-restore.test.ts +++ b/__tests__/cache-restore.test.ts @@ -135,7 +135,7 @@ describe('cache-restore', () => { await restoreCache(packageManager, ''); expect(hashFilesSpy).toHaveBeenCalled(); expect(infoSpy).toHaveBeenCalledWith( - `Cache restored from key: node-cache-${platform}-${packageManager}-v2-${fileHash}` + `Cache restored from key: node-cache-${platform}-${packageManager}-${fileHash}` ); expect(infoSpy).not.toHaveBeenCalledWith( `${packageManager} cache is not found` diff --git a/__tests__/cache-utils.test.ts b/__tests__/cache-utils.test.ts index da9c793bc..56f46425a 100644 --- a/__tests__/cache-utils.test.ts +++ b/__tests__/cache-utils.test.ts @@ -6,8 +6,7 @@ import { PackageManagerInfo, isCacheFeatureAvailable, supportedPackageManagers, - getCommandOutput, - memoizedCacheDependencies + getCommandOutput } from '../src/cache-utils'; import fs from 'fs'; import * as cacheUtils from '../src/cache-utils'; @@ -104,10 +103,6 @@ describe('cache-utils', () => { (pattern: string): Promise => MockGlobber.create(['/foo', '/bar']) ); - - Object.keys(memoizedCacheDependencies).forEach( - key => delete memoizedCacheDependencies[key] - ); }); afterEach(() => { @@ -175,25 +170,23 @@ describe('cache-utils', () => { ); it.each([ - [supportedPackageManagers.npm, ''], - [supportedPackageManagers.npm, '/dir/file.lock'], - [supportedPackageManagers.npm, '/**/file.lock'], - [supportedPackageManagers.pnpm, ''], - [supportedPackageManagers.pnpm, '/dir/file.lock'], - [supportedPackageManagers.pnpm, '/**/file.lock'], - [supportedPackageManagers.yarn, ''], [supportedPackageManagers.yarn, '/dir/file.lock'], [supportedPackageManagers.yarn, '/**/file.lock'] ])( - 'getCacheDirectoriesPaths should throw in case of having not directories', + 'getCacheDirectoriesPaths should nothrow in case of having not directories', async (packageManagerInfo, cacheDependency) => { lstatSpy.mockImplementation(arg => ({ isDirectory: () => false })); - await expect( - cacheUtils.getCacheDirectories(packageManagerInfo, cacheDependency) - ).rejects.toThrow(); //'Could not get cache folder path for /dir'); + await cacheUtils.getCacheDirectories( + packageManagerInfo, + cacheDependency + ); + expect(warningSpy).toHaveBeenCalledTimes(1); + expect(warningSpy).toHaveBeenCalledWith( + `No existing directories found containing cache-dependency-path="${cacheDependency}"` + ); } ); diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 2b16ee16b..1170e3328 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -60434,7 +60434,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectories = exports.memoizedCacheDependencies = exports.getPackageManagerInfo = exports.getCommandOutputNotEmpty = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectories = exports.getPackageManagerInfo = exports.getCommandOutputNotEmpty = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -60503,11 +60503,6 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void } }); exports.getPackageManagerInfo = getPackageManagerInfo; -/** - * glob expanding memoized because it involves potentially very deep - * traversing through the directories tree - */ -exports.memoizedCacheDependencies = {}; /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots @@ -60516,27 +60511,15 @@ exports.memoizedCacheDependencies = {}; * @return list of directories and possible */ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - let cacheDependenciesPaths; - // memoize unglobbed paths to avoid traversing FS - const memoized = exports.memoizedCacheDependencies[cacheDependencyPath]; - if (memoized) { - cacheDependenciesPaths = memoized; - } - else { - const globber = yield glob.create(cacheDependencyPath); - cacheDependenciesPaths = yield globber.glob(); - exports.memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; - } + const globber = yield glob.create(cacheDependencyPath); + const cacheDependenciesPaths = yield globber.glob(); const existingDirectories = cacheDependenciesPaths .map(path_1.default.dirname) .filter(util_1.unique()) .filter(fs_1.default.existsSync) .filter(directory => fs_1.default.lstatSync(directory).isDirectory()); - // if user explicitly pointed out some file, but it does not exist it is definitely - // not he wanted, thus we should throw an error not trying to workaround with unexpected - // result to the whole build if (!existingDirectories.length) - throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); + core.warning(`No existing directories found containing cache-dependency-path="${cacheDependencyPath}"`); return existingDirectories; }); /** diff --git a/dist/setup/index.js b/dist/setup/index.js index 24865a81d..81ecf48ff 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71153,7 +71153,7 @@ const restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, if (!fileHash) { throw new Error('Some specified paths were not resolved, unable to cache dependencies.'); } - const primaryKey = `node-cache-${platform}-${packageManager}-v2-${fileHash}`; + const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; core.debug(`primary key is ${primaryKey}`); core.saveState(constants_1.State.CachePrimaryKey, primaryKey); const cacheKey = yield cache.restoreCache(cachePaths, primaryKey); @@ -71217,7 +71217,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectories = exports.memoizedCacheDependencies = exports.getPackageManagerInfo = exports.getCommandOutputNotEmpty = exports.getCommandOutput = exports.supportedPackageManagers = void 0; +exports.isCacheFeatureAvailable = exports.isGhes = exports.getCacheDirectories = exports.getPackageManagerInfo = exports.getCommandOutputNotEmpty = exports.getCommandOutput = exports.supportedPackageManagers = void 0; const core = __importStar(__nccwpck_require__(2186)); const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); @@ -71286,11 +71286,6 @@ const getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void } }); exports.getPackageManagerInfo = getPackageManagerInfo; -/** - * glob expanding memoized because it involves potentially very deep - * traversing through the directories tree - */ -exports.memoizedCacheDependencies = {}; /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots @@ -71299,27 +71294,15 @@ exports.memoizedCacheDependencies = {}; * @return list of directories and possible */ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - let cacheDependenciesPaths; - // memoize unglobbed paths to avoid traversing FS - const memoized = exports.memoizedCacheDependencies[cacheDependencyPath]; - if (memoized) { - cacheDependenciesPaths = memoized; - } - else { - const globber = yield glob.create(cacheDependencyPath); - cacheDependenciesPaths = yield globber.glob(); - exports.memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; - } + const globber = yield glob.create(cacheDependencyPath); + const cacheDependenciesPaths = yield globber.glob(); const existingDirectories = cacheDependenciesPaths .map(path_1.default.dirname) .filter(util_1.unique()) .filter(fs_1.default.existsSync) .filter(directory => fs_1.default.lstatSync(directory).isDirectory()); - // if user explicitly pointed out some file, but it does not exist it is definitely - // not he wanted, thus we should throw an error not trying to workaround with unexpected - // result to the whole build if (!existingDirectories.length) - throw Error('No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"'); + core.warning(`No existing directories found containing cache-dependency-path="${cacheDependencyPath}"`); return existingDirectories; }); /** diff --git a/src/cache-restore.ts b/src/cache-restore.ts index e138707c2..6ac2cc755 100644 --- a/src/cache-restore.ts +++ b/src/cache-restore.ts @@ -37,7 +37,7 @@ export const restoreCache = async ( ); } - const primaryKey = `node-cache-${platform}-${packageManager}-v2-${fileHash}`; + const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; core.debug(`primary key is ${primaryKey}`); core.saveState(State.CachePrimaryKey, primaryKey); diff --git a/src/cache-utils.ts b/src/cache-utils.ts index c30e65025..0177fba03 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -110,11 +110,6 @@ export const getPackageManagerInfo = async (packageManager: string) => { } }; -/** - * glob expanding memoized because it involves potentially very deep - * traversing through the directories tree - */ -export const memoizedCacheDependencies: Record = {}; /** * Expands (converts) the string input `cache-dependency-path` to list of directories that * may be project roots @@ -125,17 +120,8 @@ export const memoizedCacheDependencies: Record = {}; const getProjectDirectoriesFromCacheDependencyPath = async ( cacheDependencyPath: string ): Promise => { - let cacheDependenciesPaths: string[]; - - // memoize unglobbed paths to avoid traversing FS - const memoized = memoizedCacheDependencies[cacheDependencyPath]; - if (memoized) { - cacheDependenciesPaths = memoized; - } else { - const globber = await glob.create(cacheDependencyPath); - cacheDependenciesPaths = await globber.glob(); - memoizedCacheDependencies[cacheDependencyPath] = cacheDependenciesPaths; - } + const globber = await glob.create(cacheDependencyPath); + const cacheDependenciesPaths = await globber.glob(); const existingDirectories: string[] = cacheDependenciesPaths .map(path.dirname) @@ -143,12 +129,9 @@ const getProjectDirectoriesFromCacheDependencyPath = async ( .filter(fs.existsSync) .filter(directory => fs.lstatSync(directory).isDirectory()); - // if user explicitly pointed out some file, but it does not exist it is definitely - // not he wanted, thus we should throw an error not trying to workaround with unexpected - // result to the whole build if (!existingDirectories.length) - throw Error( - 'No existing directories found containing `cache-dependency-path`="${cacheDependencyPath}"' + core.warning( + `No existing directories found containing cache-dependency-path="${cacheDependencyPath}"` ); return existingDirectories; From 17a48541930c3b0d064ba15c28ea5eb95d63c00e Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Fri, 16 Jun 2023 10:05:15 +0200 Subject: [PATCH 20/21] Review fixes 3 --- __tests__/cache-save.test.ts | 8 -------- dist/cache-save/index.js | 1 - dist/setup/index.js | 1 - src/cache-utils.ts | 1 - 4 files changed, 11 deletions(-) diff --git a/__tests__/cache-save.test.ts b/__tests__/cache-save.test.ts index a989d2b11..922566d63 100644 --- a/__tests__/cache-save.test.ts +++ b/__tests__/cache-save.test.ts @@ -143,14 +143,6 @@ describe('run', () => { expect(getStateSpy).toHaveBeenCalledTimes(3); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0); - /* - expect(debugSpy).toHaveBeenCalledWith( - 'Consumed yarn version is 2.2.3 (working dir: "")' - ); - expect(debugSpy).toHaveBeenCalledWith( - 'yarn\'s cache folder "/some/random/path/yarn2" configured for the root directory' - ); - */ expect(infoSpy).toHaveBeenCalledWith( `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` ); diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 1170e3328..3a8d0cee2 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -60516,7 +60516,6 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ const existingDirectories = cacheDependenciesPaths .map(path_1.default.dirname) .filter(util_1.unique()) - .filter(fs_1.default.existsSync) .filter(directory => fs_1.default.lstatSync(directory).isDirectory()); if (!existingDirectories.length) core.warning(`No existing directories found containing cache-dependency-path="${cacheDependencyPath}"`); diff --git a/dist/setup/index.js b/dist/setup/index.js index 81ecf48ff..83bf5f6a3 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71299,7 +71299,6 @@ const getProjectDirectoriesFromCacheDependencyPath = (cacheDependencyPath) => __ const existingDirectories = cacheDependenciesPaths .map(path_1.default.dirname) .filter(util_1.unique()) - .filter(fs_1.default.existsSync) .filter(directory => fs_1.default.lstatSync(directory).isDirectory()); if (!existingDirectories.length) core.warning(`No existing directories found containing cache-dependency-path="${cacheDependencyPath}"`); diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 0177fba03..ac82c4c20 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -126,7 +126,6 @@ const getProjectDirectoriesFromCacheDependencyPath = async ( const existingDirectories: string[] = cacheDependenciesPaths .map(path.dirname) .filter(unique()) - .filter(fs.existsSync) .filter(directory => fs.lstatSync(directory).isDirectory()); if (!existingDirectories.length) From e9e4944550b9caba4b088ef10f1070c711b1d63e Mon Sep 17 00:00:00 2001 From: Sergey Dolin Date: Fri, 16 Jun 2023 14:17:41 +0200 Subject: [PATCH 21/21] imporve e2e tests --- .github/workflows/e2e-cache.yml | 50 +------------------------------- __tests__/prepare-subprojects.sh | 48 ++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 49 deletions(-) create mode 100755 __tests__/prepare-subprojects.sh diff --git a/.github/workflows/e2e-cache.yml b/.github/workflows/e2e-cache.yml index 0d0da14c7..901ed87cc 100644 --- a/.github/workflows/e2e-cache.yml +++ b/.github/workflows/e2e-cache.yml @@ -146,55 +146,7 @@ jobs: - uses: actions/checkout@v3 - name: prepare sub-projects - env: - YARN_ENABLE_IMMUTABLE_INSTALLS: false - run: | - rm package.json - rm package-lock.json - echo "create yarn2 project in the sub2" - mkdir sub2 - cd sub2 - cat <package.json - { - "name": "subproject", - "dependencies": { - "random": "^3.0.6", - "uuid": "^9.0.0" - } - } - EOT - yarn set version 2.4.3 - yarn install - - echo "create yarn3 project in the sub3" - cd .. - mkdir sub3 - cd sub3 - cat <package.json - { - "name": "subproject", - "dependencies": { - "random": "^3.0.6", - "uuid": "^9.0.0" - } - } - EOT - yarn set version 3.5.1 - yarn install - - echo "create yarn1 project in the root" - cd .. - cat <package.json - { - "name": "subproject", - "dependencies": { - "random": "^3.0.6", - "uuid": "^9.0.0" - } - } - EOT - yarn set version 1.22.19 - yarn install + run: __tests__/prepare-subprojects.sh # expect # - no errors diff --git a/__tests__/prepare-subprojects.sh b/__tests__/prepare-subprojects.sh new file mode 100755 index 000000000..447cc531a --- /dev/null +++ b/__tests__/prepare-subprojects.sh @@ -0,0 +1,48 @@ +#!/bin/sh -e +export YARN_ENABLE_IMMUTABLE_INSTALLS=false +rm package.json +rm package-lock.json +echo "create yarn2 project in the sub2" +mkdir sub2 +cd sub2 +cat <package.json +{ + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } +} +EOT +yarn set version 2.4.3 +yarn install + +echo "create yarn3 project in the sub3" +cd .. +mkdir sub3 +cd sub3 +cat <package.json +{ + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } +} +EOT +yarn set version 3.5.1 +yarn install + +echo "create yarn1 project in the root" +cd .. +cat <package.json +{ + "name": "subproject", + "dependencies": { + "random": "^3.0.6", + "uuid": "^9.0.0" + } +} +EOT +yarn set version 1.22.19 +yarn install \ No newline at end of file