diff --git a/.github/workflows/__upload-quality-sarif.yml b/.github/workflows/__upload-quality-sarif.yml index d9bcbb20fe..9e1dceafc5 100644 --- a/.github/workflows/__upload-quality-sarif.yml +++ b/.github/workflows/__upload-quality-sarif.yml @@ -89,7 +89,7 @@ jobs: ref: refs/heads/main sha: 5e235361806c361d4d3f8859e3c897658025a9a2 - name: Check output from `upload-sarif` step - if: fromJSON(steps.upload-sarif.outputs.sarif-ids)[0].analysis != 'code-quality' + if: '!(fromJSON(steps.upload-sarif.outputs.sarif-ids).code-quality)' run: exit 1 env: CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/update-proxy-release.yml b/.github/workflows/update-proxy-release.yml deleted file mode 100644 index f693ac9397..0000000000 --- a/.github/workflows/update-proxy-release.yml +++ /dev/null @@ -1,99 +0,0 @@ -name: Update dependency proxy release assets -on: - workflow_dispatch: - inputs: - tag: - description: "The tag of CodeQL Bundle release that contains the proxy binaries as release assets" - type: string - required: true - -defaults: - run: - shell: bash - -jobs: - update: - name: Update code and create PR - timeout-minutes: 15 - runs-on: ubuntu-latest - permissions: - contents: write # needed to push the updated files - pull-requests: write # needed to create the PR - env: - RELEASE_TAG: ${{ inputs.tag }} - steps: - - name: Check release tag format - id: checks - run: | - if ! [[ $RELEASE_TAG =~ ^codeql-bundle-v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "Invalid release tag: expected a CodeQL bundle tag in the 'codeql-bundle-vM.N.P' format." - exit 1 - fi - - echo "target_branch=dependency-proxy/$RELEASE_TAG" >> $GITHUB_OUTPUT - - - name: Check that the release exists - env: - GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" - run: | - (gh release view --repo "$GITHUB_REPOSITORY" --json "assets" "$RELEASE_TAG" && echo "Release found.") || exit 1 - - - name: Install Node - uses: actions/setup-node@v5 - - - name: Checkout repository - uses: actions/checkout@v5 - with: - fetch-depth: 0 # ensure we have all tags and can push commits - ref: main - - - name: Update git config - run: | - git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - - - name: Update release tag and version - run: | - NOW=$(date +"%Y%m%d%H%M%S") # only used to make sure we don't fetch stale binaries from the toolcache - sed -i "s|https://github.com/github/codeql-action/releases/download/codeql-bundle-v[0-9.]\+/|https://github.com/github/codeql-action/releases/download/$RELEASE_TAG/|g" ./src/start-proxy-action.ts - sed -i "s/\"v2.0.[0-9]\+\"/\"v2.0.$NOW\"/g" ./src/start-proxy-action.ts - - - name: Compile TypeScript and commit changes - env: - TARGET_BRANCH: ${{ steps.checks.outputs.target_branch }} - run: | - set -exu - git checkout -b "$TARGET_BRANCH" - - npm run build - git add ./src/start-proxy-action.ts - git add ./lib - git commit -m "Update release used by \`start-proxy\` action" - - - name: Push changes and open PR - env: - GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" - TARGET_BRANCH: ${{ steps.checks.outputs.target_branch }} - PR_FLAG: ${{ (github.event_name == 'workflow_dispatch' && '--draft') || '--dry-run' }} - run: | - set -exu - pr_title="Update release used by \`start-proxy\` to \`$RELEASE_TAG\`" - pr_body=$(cat << EOF - This PR updates the \`start-proxy\` action to use the private registry proxy binaries that - are attached as release assets to the \`$RELEASE_TAG\` release. - - - Please do the following before merging: - - - [ ] Verify that the changes to the code are correct. - - [ ] Mark the PR as ready for review to trigger the CI. - EOF - ) - - git push origin "$TARGET_BRANCH" - gh pr create \ - --head "$TARGET_BRANCH" \ - --base "main" \ - --title "${pr_title}" \ - --body "${pr_body}" \ - $PR_FLAG diff --git a/CHANGELOG.md b/CHANGELOG.md index ab3bbca6b7..41d89f885d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ See the [releases page](https://github.com/github/codeql-action/releases) for the relevant changes to the CodeQL CLI and language packs. +## 3.30.6 - 02 Oct 2025 + +- Update default CodeQL bundle version to 2.23.2. [#3168](https://github.com/github/codeql-action/pull/3168) + ## 3.30.5 - 26 Sep 2025 - We fixed a bug that was introduced in `3.30.4` with `upload-sarif` which resulted in files without a `.sarif` extension not getting uploaded. [#3160](https://github.com/github/codeql-action/pull/3160) diff --git a/eslint.config.mjs b/eslint.config.mjs index fb4bc87ec3..bd12d12c70 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -146,6 +146,12 @@ export default [ "@typescript-eslint/prefer-regexp-exec": "off", "@typescript-eslint/require-await": "off", "@typescript-eslint/restrict-template-expressions": "off", + "@typescript-eslint/no-unused-vars": [ + "error", + { + "argsIgnorePattern": "^_", + } + ], "func-style": "off", }, }, diff --git a/lib/analyze-action-post.js b/lib/analyze-action-post.js index 4466b39598..e5ccfa9f98 100644 --- a/lib/analyze-action-post.js +++ b/lib/analyze-action-post.js @@ -26438,7 +26438,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -28542,7 +28542,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } @@ -118671,7 +118671,7 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion if (fs5.existsSync(baseTempDir)) { const outputDirs = fs5.readdirSync(baseTempDir); for (const outputDir of outputDirs) { - const sarifFiles = fs5.readdirSync(path5.resolve(baseTempDir, outputDir)).filter((f) => f.endsWith(".sarif")); + const sarifFiles = fs5.readdirSync(path5.resolve(baseTempDir, outputDir)).filter((f) => path5.extname(f) === ".sarif"); for (const sarifFile of sarifFiles) { toUpload.push(path5.resolve(baseTempDir, outputDir, sarifFile)); } diff --git a/lib/analyze-action.js b/lib/analyze-action.js index 221434663a..c60a3692a9 100644 --- a/lib/analyze-action.js +++ b/lib/analyze-action.js @@ -28149,11 +28149,11 @@ var require_out = __commonJS({ async.read(path20, getSettings(optionsOrSettingsOrCallback), callback); } exports2.stat = stat; - function statSync3(path20, optionsOrSettings) { + function statSync4(path20, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path20, settings); } - exports2.statSync = statSync3; + exports2.statSync = statSync4; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; @@ -32287,7 +32287,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -34391,7 +34391,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } @@ -90167,6 +90167,7 @@ var CodeScanning = { target: "PUT /repos/:owner/:repo/code-scanning/analysis" /* CODE_SCANNING */, sarifExtension: ".sarif", sarifPredicate: (name) => name.endsWith(CodeScanning.sarifExtension) && !CodeQuality.sarifPredicate(name), + fixCategory: (_, category) => category, sentinelPrefix: "CODEQL_UPLOAD_SARIF_" }; var CodeQuality = { @@ -90175,6 +90176,7 @@ var CodeQuality = { target: "PUT /repos/:owner/:repo/code-quality/analysis" /* CODE_QUALITY */, sarifExtension: ".quality.sarif", sarifPredicate: (name) => name.endsWith(CodeQuality.sarifExtension), + fixCategory: fixCodeQualityCategory, sentinelPrefix: "CODEQL_UPLOAD_QUALITY_SARIF_" }; @@ -90634,8 +90636,8 @@ var path8 = __toESM(require("path")); var semver4 = __toESM(require_semver2()); // src/defaults.json -var bundleVersion = "codeql-bundle-v2.23.1"; -var cliVersion = "2.23.1"; +var bundleVersion = "codeql-bundle-v2.23.2"; +var cliVersion = "2.23.2"; // src/overlay-database-utils.ts var crypto = __toESM(require("crypto")); @@ -93338,6 +93340,7 @@ async function makeGlobber(patterns) { return glob.create(patterns.join("\n")); } async function uploadDependencyCaches(config, logger, minimizeJavaJars) { + const status = []; for (const language of config.languages) { const cacheConfig = getDefaultCacheConfig()[language]; if (cacheConfig === void 0) { @@ -93348,6 +93351,7 @@ async function uploadDependencyCaches(config, logger, minimizeJavaJars) { } const globber = await makeGlobber(cacheConfig.hash); if ((await globber.glob()).length === 0) { + status.push({ language, result: "no-hash" /* NoHash */ }); logger.info( `Skipping upload of dependency cache for ${language} as we cannot calculate a hash for the cache key.` ); @@ -93355,6 +93359,7 @@ async function uploadDependencyCaches(config, logger, minimizeJavaJars) { } const size = await getTotalCacheSize(cacheConfig.paths, logger, true); if (size === 0) { + status.push({ language, result: "empty" /* Empty */ }); logger.info( `Skipping upload of dependency cache for ${language} since it is empty.` ); @@ -93365,18 +93370,28 @@ async function uploadDependencyCaches(config, logger, minimizeJavaJars) { `Uploading cache of size ${size} for ${language} with key ${key}...` ); try { + const start = performance.now(); await actionsCache3.saveCache(cacheConfig.paths, key); + const upload_duration_ms = Math.round(performance.now() - start); + status.push({ + language, + result: "stored" /* Stored */, + upload_size_bytes: Math.round(size), + upload_duration_ms + }); } catch (error2) { if (error2 instanceof actionsCache3.ReserveCacheError) { logger.info( `Not uploading cache for ${language}, because ${key} is already in use.` ); logger.debug(error2.message); + status.push({ language, result: "duplicate" /* Duplicate */ }); } else { throw error2; } } } + return status; } async function cacheKey2(language, cacheConfig, minimizeJavaJars = false) { const hash2 = await glob.hashFiles(cacheConfig.hash.join("\n")); @@ -93826,7 +93841,7 @@ async function runQueries(sarifFolder, memoryFlag, addSnippetsFlag, threadsFlag, logger.info(`Interpreting ${analysis.name} results for ${language}`); let category = automationDetailsId; if (analysis.kind === "code-quality" /* CodeQuality */) { - category = fixCodeQualityCategory(logger, automationDetailsId); + category = analysis.fixCategory(logger, automationDetailsId); } const sarifFile = path16.join( sarifFolder, @@ -95699,6 +95714,7 @@ async function uploadSpecifiedFiles(sarifPaths, checkoutPath, category, features logger.info(`Processing sarif files: ${JSON.stringify(sarifPaths)}`); const gitHubVersion = await getGitHubVersion(); let sarif; + category = uploadTarget.fixCategory(logger, category); if (sarifPaths.length > 1) { for (const sarifPath of sarifPaths) { const parsedSarif = readSarifFile(sarifPath); @@ -95941,7 +95957,7 @@ function filterAlertsByDiffRange(logger, sarif) { } // src/analyze-action.ts -async function sendStatusReport2(startedAt, config, stats, error2, trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, trapCacheCleanup, logger) { +async function sendStatusReport2(startedAt, config, stats, error2, trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, trapCacheCleanup, dependencyCacheResults, logger) { const status = getActionsStatus(error2, stats?.analyze_failure_language); const statusReportBase = await createStatusReportBase( "finish" /* Analyze */, @@ -95958,7 +95974,8 @@ async function sendStatusReport2(startedAt, config, stats, error2, trapCacheUplo ...statusReportBase, ...stats || {}, ...dbCreationTimings || {}, - ...trapCacheCleanup || {} + ...trapCacheCleanup || {}, + dependency_caching_upload_results: dependencyCacheResults }; if (config && didUploadTrapCaches) { const trapCacheUploadStatusReport = { @@ -96039,6 +96056,7 @@ async function run() { let trapCacheUploadTime = void 0; let dbCreationTimings = void 0; let didUploadTrapCaches = false; + let dependencyCacheResults; initializeEnvironment(getActionVersion()); persistInputs(); const logger = getActionsLogger(); @@ -96146,16 +96164,14 @@ async function run() { core14.setOutput("sarif-id", uploadResult.sarifID); } if (isCodeQualityEnabled(config)) { + const analysis = CodeQuality; const qualityUploadResult = await uploadFiles( outputDir, getRequiredInput("checkout_path"), - fixCodeQualityCategory( - logger, - getOptionalInput("category") - ), + getOptionalInput("category"), features, logger, - CodeQuality + analysis ); core14.setOutput("quality-sarif-id", qualityUploadResult.sarifID); } @@ -96177,7 +96193,11 @@ async function run() { "java_minimize_dependency_jars" /* JavaMinimizeDependencyJars */, codeql ); - await uploadDependencyCaches(config, logger, minimizeJavaJars); + dependencyCacheResults = await uploadDependencyCaches( + config, + logger, + minimizeJavaJars + ); } if (isInTestMode()) { logger.debug("In test mode. Waiting for processing is disabled."); @@ -96208,6 +96228,7 @@ async function run() { dbCreationTimings, didUploadTrapCaches, trapCacheCleanupTelemetry, + dependencyCacheResults, logger ); return; @@ -96225,6 +96246,7 @@ async function run() { dbCreationTimings, didUploadTrapCaches, trapCacheCleanupTelemetry, + dependencyCacheResults, logger ); } else if (runStats) { @@ -96237,6 +96259,7 @@ async function run() { dbCreationTimings, didUploadTrapCaches, trapCacheCleanupTelemetry, + dependencyCacheResults, logger ); } else { @@ -96249,6 +96272,7 @@ async function run() { dbCreationTimings, didUploadTrapCaches, trapCacheCleanupTelemetry, + dependencyCacheResults, logger ); } diff --git a/lib/autobuild-action.js b/lib/autobuild-action.js index cf4e82a6bb..b65cb80434 100644 --- a/lib/autobuild-action.js +++ b/lib/autobuild-action.js @@ -26438,7 +26438,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -28542,7 +28542,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } @@ -78295,8 +78295,8 @@ var path3 = __toESM(require("path")); var semver4 = __toESM(require_semver2()); // src/defaults.json -var bundleVersion = "codeql-bundle-v2.23.1"; -var cliVersion = "2.23.1"; +var bundleVersion = "codeql-bundle-v2.23.2"; +var cliVersion = "2.23.2"; // src/overlay-database-utils.ts var fs2 = __toESM(require("fs")); diff --git a/lib/defaults.json b/lib/defaults.json index dbc0d5e258..3c4a3ddbef 100644 --- a/lib/defaults.json +++ b/lib/defaults.json @@ -1,6 +1,6 @@ { - "bundleVersion": "codeql-bundle-v2.23.1", - "cliVersion": "2.23.1", - "priorBundleVersion": "codeql-bundle-v2.23.0", - "priorCliVersion": "2.23.0" + "bundleVersion": "codeql-bundle-v2.23.2", + "cliVersion": "2.23.2", + "priorBundleVersion": "codeql-bundle-v2.23.1", + "priorCliVersion": "2.23.1" } diff --git a/lib/init-action-post.js b/lib/init-action-post.js index 63f65d1e55..ff5a35731f 100644 --- a/lib/init-action-post.js +++ b/lib/init-action-post.js @@ -28149,11 +28149,11 @@ var require_out = __commonJS({ async.read(path19, getSettings(optionsOrSettingsOrCallback), callback); } exports2.stat = stat; - function statSync2(path19, optionsOrSettings) { + function statSync3(path19, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path19, settings); } - exports2.statSync = statSync2; + exports2.statSync = statSync3; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; @@ -32287,7 +32287,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -34391,7 +34391,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } @@ -128337,6 +128337,9 @@ function getWorkflowRunAttempt() { function isSelfHostedRunner() { return process.env.RUNNER_ENVIRONMENT === "self-hosted"; } +function isDefaultSetup() { + return getWorkflowEventName() === "dynamic"; +} function prettyPrintInvocation(cmd, args) { return [cmd, ...args].map((x) => x.includes(" ") ? `'${x}'` : x).join(" "); } @@ -128402,6 +128405,30 @@ var restoreInputs = function() { } } }; +var qualityCategoryMapping = { + "c#": "csharp", + cpp: "c-cpp", + c: "c-cpp", + "c++": "c-cpp", + java: "java-kotlin", + javascript: "javascript-typescript", + typescript: "javascript-typescript", + kotlin: "java-kotlin" +}; +function fixCodeQualityCategory(logger, category) { + if (category !== void 0 && isDefaultSetup() && category.startsWith("/language:")) { + const language = category.substring("/language:".length); + const mappedLanguage = qualityCategoryMapping[language]; + if (mappedLanguage) { + const newCategory = `/language:${mappedLanguage}`; + logger.info( + `Adjusted category for Code Quality from '${category}' to '${newCategory}'.` + ); + return newCategory; + } + } + return category; +} // src/api-client.ts var core5 = __toESM(require_core()); @@ -128534,6 +128561,18 @@ function computeAutomationID(analysis_key, environment) { } return automationID; } +async function listActionsCaches(key, ref) { + const repositoryNwo = getRepositoryNwo(); + return await getApiClient().paginate( + "GET /repos/{owner}/{repo}/actions/caches", + { + owner: repositoryNwo.owner, + repo: repositoryNwo.repo, + key, + ref + } + ); +} function wrapApiConfigurationError(e) { if (isHTTPError(e)) { if (e.message.includes("API rate limit exceeded for installation") || e.message.includes("commit not found") || e.message.includes("Resource not accessible by integration") || /ref .* not found in this repository/.test(e.message)) { @@ -128547,6 +128586,9 @@ function wrapApiConfigurationError(e) { return e; } +// src/caching-utils.ts +var core6 = __toESM(require_core()); + // src/codeql.ts var fs13 = __toESM(require("fs")); var path13 = __toESM(require("path")); @@ -128807,6 +128849,7 @@ var CodeScanning = { target: "PUT /repos/:owner/:repo/code-scanning/analysis" /* CODE_SCANNING */, sarifExtension: ".sarif", sarifPredicate: (name) => name.endsWith(CodeScanning.sarifExtension) && !CodeQuality.sarifPredicate(name), + fixCategory: (_2, category) => category, sentinelPrefix: "CODEQL_UPLOAD_SARIF_" }; var CodeQuality = { @@ -128815,12 +128858,10 @@ var CodeQuality = { target: "PUT /repos/:owner/:repo/code-quality/analysis" /* CODE_QUALITY */, sarifExtension: ".quality.sarif", sarifPredicate: (name) => name.endsWith(CodeQuality.sarifExtension), + fixCategory: fixCodeQualityCategory, sentinelPrefix: "CODEQL_UPLOAD_QUALITY_SARIF_" }; -// src/caching-utils.ts -var core6 = __toESM(require_core()); - // src/config/db-config.ts var semver2 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { @@ -128840,8 +128881,8 @@ var path8 = __toESM(require("path")); var semver4 = __toESM(require_semver2()); // src/defaults.json -var bundleVersion = "codeql-bundle-v2.23.1"; -var cliVersion = "2.23.1"; +var bundleVersion = "codeql-bundle-v2.23.2"; +var cliVersion = "2.23.2"; // src/overlay-database-utils.ts var fs6 = __toESM(require("fs")); @@ -131169,6 +131210,22 @@ var core11 = __toESM(require_core()); // src/dependency-caching.ts var actionsCache3 = __toESM(require_cache3()); var glob = __toESM(require_glob3()); +var CODEQL_DEPENDENCY_CACHE_PREFIX = "codeql-dependencies"; +async function getDependencyCacheUsage(logger) { + try { + const caches = await listActionsCaches(CODEQL_DEPENDENCY_CACHE_PREFIX); + const totalSize = caches.reduce( + (acc, cache) => acc + (cache.size_in_bytes ?? 0), + 0 + ); + return { count: caches.length, size_bytes: totalSize }; + } catch (err) { + logger.warning( + `Unable to retrieve information about dependency cache usage: ${getErrorMessage(err)}` + ); + } + return void 0; +} // src/analyze.ts function dbIsFinalized(config, language, logger) { @@ -133133,6 +133190,7 @@ async function uploadSpecifiedFiles(sarifPaths, checkoutPath, category, features logger.info(`Processing sarif files: ${JSON.stringify(sarifPaths)}`); const gitHubVersion = await getGitHubVersion(); let sarif; + category = uploadTarget.fixCategory(logger, category); if (sarifPaths.length > 1) { for (const sarifPath of sarifPaths) { const parsedSarif = readSarifFile(sarifPath); @@ -133718,6 +133776,7 @@ async function runWrapper() { const startedAt = /* @__PURE__ */ new Date(); let config; let uploadFailedSarifResult; + let dependencyCachingUsage; try { restoreInputs(); const gitHubVersion = await getGitHubVersion(); @@ -133745,6 +133804,9 @@ async function runWrapper() { features, logger ); + if (await isAnalyzingDefaultBranch() && config.dependencyCachingEnabled !== "none" /* None */) { + dependencyCachingUsage = await getDependencyCacheUsage(logger); + } } } catch (unwrappedError) { const error2 = wrapError(unwrappedError); @@ -133778,7 +133840,8 @@ async function runWrapper() { const statusReport = { ...statusReportBase, ...uploadFailedSarifResult, - job_status: getFinalJobStatus() + job_status: getFinalJobStatus(), + dependency_caching_usage: dependencyCachingUsage }; logger.info("Sending status report for init-post step."); await sendStatusReport(statusReport); diff --git a/lib/init-action.js b/lib/init-action.js index 703107c5ad..8e246aebb0 100644 --- a/lib/init-action.js +++ b/lib/init-action.js @@ -32287,7 +32287,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -34391,7 +34391,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } @@ -86563,8 +86563,8 @@ var path9 = __toESM(require("path")); var semver4 = __toESM(require_semver2()); // src/defaults.json -var bundleVersion = "codeql-bundle-v2.23.1"; -var cliVersion = "2.23.1"; +var bundleVersion = "codeql-bundle-v2.23.2"; +var cliVersion = "2.23.2"; // src/overlay-database-utils.ts var crypto = __toESM(require("crypto")); @@ -88184,7 +88184,7 @@ async function makeGlobber(patterns) { return glob.create(patterns.join("\n")); } async function downloadDependencyCaches(languages, logger, minimizeJavaJars) { - const restoredCaches = []; + const status = []; for (const language of languages) { const cacheConfig = getDefaultCacheConfig()[language]; if (cacheConfig === void 0) { @@ -88195,6 +88195,7 @@ async function downloadDependencyCaches(languages, logger, minimizeJavaJars) { } const globber = await makeGlobber(cacheConfig.hash); if ((await globber.glob()).length === 0) { + status.push({ language, hit_kind: "no-hash" /* NoHash */ }); logger.info( `Skipping download of dependency cache for ${language} as we cannot calculate a hash for the cache key.` ); @@ -88209,19 +88210,23 @@ async function downloadDependencyCaches(languages, logger, minimizeJavaJars) { ", " )}` ); + const start = performance.now(); const hitKey = await actionsCache3.restoreCache( cacheConfig.paths, primaryKey, restoreKeys ); + const download_duration_ms = Math.round(performance.now() - start); if (hitKey !== void 0) { logger.info(`Cache hit on key ${hitKey} for ${language}.`); - restoredCaches.push(language); + const hit_kind = hitKey === primaryKey ? "exact" /* Exact */ : "partial" /* Partial */; + status.push({ language, hit_kind, download_duration_ms }); } else { + status.push({ language, hit_kind: "miss" /* Miss */ }); logger.info(`No suitable cache found for ${language}.`); } } - return restoredCaches; + return status; } async function cacheKey2(language, cacheConfig, minimizeJavaJars = false) { const hash = await glob.hashFiles(cacheConfig.hash.join("\n")); @@ -90324,7 +90329,7 @@ async function sendStatusReport(statusReport) { ); } } -async function createInitWithConfigStatusReport(config, initStatusReport, configFile, totalCacheSize, overlayBaseDatabaseStats) { +async function createInitWithConfigStatusReport(config, initStatusReport, configFile, totalCacheSize, overlayBaseDatabaseStats, dependencyCachingResults) { const languages = config.languages.join(","); const paths = (config.originalUserInput.paths || []).join(","); const pathsIgnore = (config.originalUserInput["paths-ignore"] || []).join( @@ -90361,6 +90366,7 @@ async function createInitWithConfigStatusReport(config, initStatusReport, config trap_cache_download_duration_ms: Math.round(config.trapCacheDownloadTime), overlay_base_database_download_size_bytes: overlayBaseDatabaseStats?.databaseSizeBytes, overlay_base_database_download_duration_ms: overlayBaseDatabaseStats?.databaseDownloadDurationMs, + dependency_caching_restore_results: dependencyCachingResults, query_filters: JSON.stringify( config.originalUserInput["query-filters"] ?? [] ), @@ -90543,7 +90549,7 @@ async function getWorkflowAbsolutePath(logger) { } // src/init-action.ts -async function sendCompletedStatusReport(startedAt, config, configFile, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, overlayBaseDatabaseStats, logger, error2) { +async function sendCompletedStatusReport(startedAt, config, configFile, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, overlayBaseDatabaseStats, dependencyCachingResults, logger, error2) { const statusReportBase = await createStatusReportBase( "init" /* Init */, getActionsStatus(error2), @@ -90580,7 +90586,8 @@ async function sendCompletedStatusReport(startedAt, config, configFile, toolsDow Math.round( await getTotalCacheSize(Object.values(config.trapCaches), logger) ), - overlayBaseDatabaseStats + overlayBaseDatabaseStats, + dependencyCachingResults ); await sendStatusReport({ ...initWithConfigStatusReport, @@ -90744,6 +90751,7 @@ async function run() { return; } let overlayBaseDatabaseStats; + let dependencyCachingResults; try { if (config.overlayDatabaseMode === "overlay" /* Overlay */ && config.useOverlayDatabaseCaching) { overlayBaseDatabaseStats = await downloadOverlayBaseDatabaseFromCache( @@ -90888,7 +90896,7 @@ exec ${goBinaryPath} "$@"` codeql ); if (shouldRestoreCache(config.dependencyCachingEnabled)) { - await downloadDependencyCaches( + dependencyCachingResults = await downloadDependencyCaches( config.languages, logger, minimizeJavaJars @@ -90993,6 +91001,7 @@ exec ${goBinaryPath} "$@"` toolsSource, toolsVersion, overlayBaseDatabaseStats, + dependencyCachingResults, logger, error2 ); @@ -91010,6 +91019,7 @@ exec ${goBinaryPath} "$@"` toolsSource, toolsVersion, overlayBaseDatabaseStats, + dependencyCachingResults, logger ); } diff --git a/lib/resolve-environment-action.js b/lib/resolve-environment-action.js index 816fa8eed2..8ace1ec0bc 100644 --- a/lib/resolve-environment-action.js +++ b/lib/resolve-environment-action.js @@ -26438,7 +26438,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -28542,7 +28542,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } diff --git a/lib/start-proxy-action-post.js b/lib/start-proxy-action-post.js index 98cff4159e..e0ff1691ae 100644 --- a/lib/start-proxy-action-post.js +++ b/lib/start-proxy-action-post.js @@ -26438,7 +26438,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -28542,7 +28542,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } diff --git a/lib/start-proxy-action.js b/lib/start-proxy-action.js index 56006078a3..91a4880ef2 100644 --- a/lib/start-proxy-action.js +++ b/lib/start-proxy-action.js @@ -5,9 +5,16 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) @@ -24,6 +31,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // node_modules/@actions/core/lib/utils.js var require_utils = __commonJS({ @@ -61,7 +69,7 @@ var require_utils = __commonJS({ var require_command = __commonJS({ "node_modules/@actions/core/lib/command.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -74,27 +82,27 @@ var require_command = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.issue = exports2.issueCommand = void 0; - var os = __importStar(require("os")); + var os2 = __importStar4(require("os")); var utils_1 = require_utils(); function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); + process.stdout.write(cmd.toString() + os2.EOL); } exports2.issueCommand = issueCommand; function issue(name, message = "") { @@ -118,14 +126,14 @@ var require_command = __commonJS({ let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { + const val2 = this.properties[key]; + if (val2) { if (first) { first = false; } else { cmdStr += ","; } - cmdStr += `${key}=${escapeProperty(val)}`; + cmdStr += `${key}=${escapeProperty(val2)}`; } } } @@ -147,7 +155,7 @@ var require_command = __commonJS({ var require_file_command = __commonJS({ "node_modules/@actions/core/lib/file-command.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -160,25 +168,25 @@ var require_file_command = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.prepareKeyValueMessage = exports2.issueFileCommand = void 0; - var crypto = __importStar(require("crypto")); - var fs = __importStar(require("fs")); - var os = __importStar(require("os")); + var crypto = __importStar4(require("crypto")); + var fs = __importStar4(require("fs")); + var os2 = __importStar4(require("os")); var utils_1 = require_utils(); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; @@ -188,7 +196,7 @@ var require_file_command = __commonJS({ if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os2.EOL}`, { encoding: "utf8" }); } @@ -202,7 +210,7 @@ var require_file_command = __commonJS({ if (convertedValue.includes(delimiter)) { throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; + return `${key}<<${delimiter}${os2.EOL}${convertedValue}${os2.EOL}${delimiter}`; } exports2.prepareKeyValueMessage = prepareKeyValueMessage; } @@ -393,7 +401,7 @@ var require_tunnel = __commonJS({ connectOptions.headers = connectOptions.headers || {}; connectOptions.headers["Proxy-Authorization"] = "Basic " + new Buffer(connectOptions.proxyAuth).toString("base64"); } - debug("making CONNECT request"); + debug3("making CONNECT request"); var connectReq = self2.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; connectReq.once("response", onResponse); @@ -413,7 +421,7 @@ var require_tunnel = __commonJS({ connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { - debug( + debug3( "tunneling socket could not be established, statusCode=%d", res.statusCode ); @@ -425,7 +433,7 @@ var require_tunnel = __commonJS({ return; } if (head.length > 0) { - debug("got illegal response body from proxy"); + debug3("got illegal response body from proxy"); socket.destroy(); var error2 = new Error("got illegal response body from proxy"); error2.code = "ECONNRESET"; @@ -433,13 +441,13 @@ var require_tunnel = __commonJS({ self2.removeSocket(placeholder); return; } - debug("tunneling connection has established"); + debug3("tunneling connection has established"); self2.sockets[self2.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); - debug( + debug3( "tunneling socket could not be established, cause=%s\n", cause.message, cause.stack @@ -501,9 +509,9 @@ var require_tunnel = __commonJS({ } return target; } - var debug; + var debug3; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { + debug3 = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === "string") { args[0] = "TUNNEL: " + args[0]; @@ -513,10 +521,10 @@ var require_tunnel = __commonJS({ console.error.apply(console, args); }; } else { - debug = function() { + debug3 = function() { }; } - exports2.debug = debug; + exports2.debug = debug3; } }); @@ -1078,8 +1086,8 @@ var require_util = __commonJS({ } } var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/; - function parseKeepAliveTimeout(val) { - const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR); + function parseKeepAliveTimeout(val2) { + const m = val2.toString().match(KEEPALIVE_TIMEOUT_EXPR); return m ? parseInt(m[1], 10) * 1e3 : null; } function headerNameToString(value) { @@ -1089,19 +1097,19 @@ var require_util = __commonJS({ if (!Array.isArray(headers)) return headers; for (let i = 0; i < headers.length; i += 2) { const key = headers[i].toString().toLowerCase(); - let val = obj[key]; - if (!val) { + let val2 = obj[key]; + if (!val2) { if (Array.isArray(headers[i + 1])) { obj[key] = headers[i + 1].map((x) => x.toString("utf8")); } else { obj[key] = headers[i + 1].toString("utf8"); } } else { - if (!Array.isArray(val)) { - val = [val]; - obj[key] = val; + if (!Array.isArray(val2)) { + val2 = [val2]; + obj[key] = val2; } - val.push(headers[i + 1].toString("utf8")); + val2.push(headers[i + 1].toString("utf8")); } } if ("content-length" in obj && "content-disposition" in obj) { @@ -1115,14 +1123,14 @@ var require_util = __commonJS({ let contentDispositionIdx = -1; for (let n = 0; n < headers.length; n += 2) { const key = headers[n + 0].toString(); - const val = headers[n + 1].toString("utf8"); + const val2 = headers[n + 1].toString("utf8"); if (key.length === 14 && (key === "content-length" || key.toLowerCase() === "content-length")) { - ret.push(key, val); + ret.push(key, val2); hasContentLength = true; } else if (key.length === 19 && (key === "content-disposition" || key.toLowerCase() === "content-disposition")) { - contentDispositionIdx = ret.push(key, val) - 1; + contentDispositionIdx = ret.push(key, val2) - 1; } else { - ret.push(key, val); + ret.push(key, val2); } } if (hasContentLength && contentDispositionIdx !== -1) { @@ -1192,16 +1200,16 @@ var require_util = __commonJS({ yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); } } - var ReadableStream; + var ReadableStream2; function ReadableStreamFrom(iterable) { - if (!ReadableStream) { - ReadableStream = require("stream/web").ReadableStream; + if (!ReadableStream2) { + ReadableStream2 = require("stream/web").ReadableStream; } - if (ReadableStream.from) { - return ReadableStream.from(convertIterableToBuffer(iterable)); + if (ReadableStream2.from) { + return ReadableStream2.from(convertIterableToBuffer(iterable)); } let iterator; - return new ReadableStream( + return new ReadableStream2( { async start() { iterator = iterable[Symbol.asyncIterator](); @@ -1251,13 +1259,13 @@ var require_util = __commonJS({ return () => signal.removeListener("abort", listener); } var hasToWellFormed = !!String.prototype.toWellFormed; - function toUSVString(val) { + function toUSVString(val2) { if (hasToWellFormed) { - return `${val}`.toWellFormed(); + return `${val2}`.toWellFormed(); } else if (nodeUtil.toUSVString) { - return nodeUtil.toUSVString(val); + return nodeUtil.toUSVString(val2); } - return `${val}`; + return `${val2}`; } function parseRangeHeader(range) { if (range == null || range === "") return { start: 0, end: null, size: null }; @@ -1534,11 +1542,11 @@ var require_PartStream = __commonJS({ "node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js"(exports2, module2) { "use strict"; var inherits = require("node:util").inherits; - var ReadableStream = require("node:stream").Readable; + var ReadableStream2 = require("node:stream").Readable; function PartStream(opts) { - ReadableStream.call(this, opts); + ReadableStream2.call(this, opts); } - inherits(PartStream, ReadableStream); + inherits(PartStream, ReadableStream2); PartStream.prototype._read = function(n) { }; module2.exports = PartStream; @@ -4122,12 +4130,12 @@ var require_util2 = __commonJS({ errorSteps(e); } } - var ReadableStream = globalThis.ReadableStream; + var ReadableStream2 = globalThis.ReadableStream; function isReadableStreamLike(stream) { - if (!ReadableStream) { - ReadableStream = require("stream/web").ReadableStream; + if (!ReadableStream2) { + ReadableStream2 = require("stream/web").ReadableStream; } - return stream instanceof ReadableStream || stream[Symbol.toStringTag] === "ReadableStream" && typeof stream.tee === "function"; + return stream instanceof ReadableStream2 || stream[Symbol.toStringTag] === "ReadableStream" && typeof stream.tee === "function"; } var MAXIMUM_ARGUMENT_LENGTH = 65535; function isomorphicDecode(input) { @@ -4914,7 +4922,7 @@ var require_file = __commonJS({ var { parseMIMEType, serializeAMimeType } = require_dataURL(); var { kEnumerableProperty } = require_util(); var encoder = new TextEncoder(); - var File = class _File extends Blob2 { + var File2 = class _File extends Blob2 { constructor(fileBits, fileName, options = {}) { webidl.argumentLengthCheck(arguments, 2, { header: "File constructor" }); fileBits = webidl.converters["sequence"](fileBits); @@ -5002,7 +5010,7 @@ var require_file = __commonJS({ return "File"; } }; - Object.defineProperties(File.prototype, { + Object.defineProperties(File2.prototype, { [Symbol.toStringTag]: { value: "File", configurable: true @@ -5082,9 +5090,9 @@ var require_file = __commonJS({ return s.replace(/\r?\n/g, nativeLineEnding); } function isFileLike(object) { - return NativeFile && object instanceof NativeFile || object instanceof File || object && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && object[Symbol.toStringTag] === "File"; + return NativeFile && object instanceof NativeFile || object instanceof File2 || object && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && object[Symbol.toStringTag] === "File"; } - module2.exports = { File, FileLike, isFileLike }; + module2.exports = { File: File2, FileLike, isFileLike }; } }); @@ -5097,8 +5105,8 @@ var require_formdata = __commonJS({ var { File: UndiciFile, FileLike, isFileLike } = require_file(); var { webidl } = require_webidl(); var { Blob: Blob2, File: NativeFile } = require("buffer"); - var File = NativeFile ?? UndiciFile; - var FormData = class _FormData { + var File2 = NativeFile ?? UndiciFile; + var FormData2 = class _FormData { constructor(form) { if (form !== void 0) { throw webidl.errors.conversionFailed({ @@ -5215,8 +5223,8 @@ var require_formdata = __commonJS({ } } }; - FormData.prototype[Symbol.iterator] = FormData.prototype.entries; - Object.defineProperties(FormData.prototype, { + FormData2.prototype[Symbol.iterator] = FormData2.prototype.entries; + Object.defineProperties(FormData2.prototype, { [Symbol.toStringTag]: { value: "FormData", configurable: true @@ -5228,19 +5236,19 @@ var require_formdata = __commonJS({ value = Buffer.from(value).toString("utf8"); } else { if (!isFileLike(value)) { - value = value instanceof Blob2 ? new File([value], "blob", { type: value.type }) : new FileLike(value, "blob", { type: value.type }); + value = value instanceof Blob2 ? new File2([value], "blob", { type: value.type }) : new FileLike(value, "blob", { type: value.type }); } if (filename !== void 0) { const options = { type: value.type, lastModified: value.lastModified }; - value = NativeFile && value instanceof NativeFile || value instanceof UndiciFile ? new File([value], filename, options) : new FileLike(value, filename, options); + value = NativeFile && value instanceof NativeFile || value instanceof UndiciFile ? new File2([value], filename, options) : new FileLike(value, filename, options); } } return { name, value }; } - module2.exports = { FormData }; + module2.exports = { FormData: FormData2 }; } }); @@ -5258,7 +5266,7 @@ var require_body = __commonJS({ createDeferredPromise, fullyReadBody } = require_util2(); - var { FormData } = require_formdata(); + var { FormData: FormData2 } = require_formdata(); var { kState } = require_symbols2(); var { webidl } = require_webidl(); var { DOMException: DOMException2, structuredClone } = require_constants2(); @@ -5276,21 +5284,21 @@ var require_body = __commonJS({ } catch { random = (max) => Math.floor(Math.random(max)); } - var ReadableStream = globalThis.ReadableStream; - var File = NativeFile ?? UndiciFile; + var ReadableStream2 = globalThis.ReadableStream; + var File2 = NativeFile ?? UndiciFile; var textEncoder = new TextEncoder(); var textDecoder = new TextDecoder(); function extractBody(object, keepalive = false) { - if (!ReadableStream) { - ReadableStream = require("stream/web").ReadableStream; + if (!ReadableStream2) { + ReadableStream2 = require("stream/web").ReadableStream; } let stream = null; - if (object instanceof ReadableStream) { + if (object instanceof ReadableStream2) { stream = object; } else if (isBlobLike(object)) { stream = object.stream(); } else { - stream = new ReadableStream({ + stream = new ReadableStream2({ async pull(controller) { controller.enqueue( typeof source === "string" ? textEncoder.encode(source) : source @@ -5380,14 +5388,14 @@ Content-Type: ${value.type || "application/octet-stream"}\r "Response body object should not be disturbed or locked" ); } - stream = object instanceof ReadableStream ? object : ReadableStreamFrom(object); + stream = object instanceof ReadableStream2 ? object : ReadableStreamFrom(object); } if (typeof source === "string" || util.isBuffer(source)) { length = Buffer.byteLength(source); } if (action != null) { let iterator; - stream = new ReadableStream({ + stream = new ReadableStream2({ async start() { iterator = action(object)[Symbol.asyncIterator](); }, @@ -5414,10 +5422,10 @@ Content-Type: ${value.type || "application/octet-stream"}\r return [body, type2]; } function safelyExtractBody(object, keepalive = false) { - if (!ReadableStream) { - ReadableStream = require("stream/web").ReadableStream; + if (!ReadableStream2) { + ReadableStream2 = require("stream/web").ReadableStream; } - if (object instanceof ReadableStream) { + if (object instanceof ReadableStream2) { assert(!util.isDisturbed(object), "The body has already been consumed."); assert(!object.locked, "The stream is locked."); } @@ -5487,7 +5495,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r if (/multipart\/form-data/.test(contentType)) { const headers = {}; for (const [key, value] of this.headers) headers[key.toLowerCase()] = value; - const responseFormData = new FormData(); + const responseFormData = new FormData2(); let busboy; try { busboy = new Busboy({ @@ -5512,14 +5520,14 @@ Content-Type: ${value.type || "application/octet-stream"}\r }); value.on("end", () => { chunks.push(Buffer.from(base64chunk, "base64")); - responseFormData.append(name, new File(chunks, filename, { type: mimeType })); + responseFormData.append(name, new File2(chunks, filename, { type: mimeType })); }); } else { value.on("data", (chunk) => { chunks.push(chunk); }); value.on("end", () => { - responseFormData.append(name, new File(chunks, filename, { type: mimeType })); + responseFormData.append(name, new File2(chunks, filename, { type: mimeType })); }); } }); @@ -5547,7 +5555,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r } catch (err) { throw Object.assign(new TypeError(), { cause: err }); } - const formData = new FormData(); + const formData = new FormData2(); for (const [name, value] of entries) { formData.append(name, value); } @@ -5924,41 +5932,41 @@ var require_request = __commonJS({ return headers; } }; - function processHeaderValue(key, val, skipAppend) { - if (val && typeof val === "object") { + function processHeaderValue(key, val2, skipAppend) { + if (val2 && typeof val2 === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } - val = val != null ? `${val}` : ""; - if (headerCharRegex.exec(val) !== null) { + val2 = val2 != null ? `${val2}` : ""; + if (headerCharRegex.exec(val2) !== null) { throw new InvalidArgumentError(`invalid ${key} header`); } - return skipAppend ? val : `${key}: ${val}\r + return skipAppend ? val2 : `${key}: ${val2}\r `; } - function processHeader(request, key, val, skipAppend = false) { - if (val && (typeof val === "object" && !Array.isArray(val))) { + function processHeader(request, key, val2, skipAppend = false) { + if (val2 && (typeof val2 === "object" && !Array.isArray(val2))) { throw new InvalidArgumentError(`invalid ${key} header`); - } else if (val === void 0) { + } else if (val2 === void 0) { return; } if (request.host === null && key.length === 4 && key.toLowerCase() === "host") { - if (headerCharRegex.exec(val) !== null) { + if (headerCharRegex.exec(val2) !== null) { throw new InvalidArgumentError(`invalid ${key} header`); } - request.host = val; + request.host = val2; } else if (request.contentLength === null && key.length === 14 && key.toLowerCase() === "content-length") { - request.contentLength = parseInt(val, 10); + request.contentLength = parseInt(val2, 10); if (!Number.isFinite(request.contentLength)) { throw new InvalidArgumentError("invalid content-length header"); } } else if (request.contentType === null && key.length === 12 && key.toLowerCase() === "content-type") { - request.contentType = val; - if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend); - else request.headers += processHeaderValue(key, val); + request.contentType = val2; + if (skipAppend) request.headers[key] = processHeaderValue(key, val2, skipAppend); + else request.headers += processHeaderValue(key, val2); } else if (key.length === 17 && key.toLowerCase() === "transfer-encoding") { throw new InvalidArgumentError("invalid transfer-encoding header"); } else if (key.length === 10 && key.toLowerCase() === "connection") { - const value = typeof val === "string" ? val.toLowerCase() : null; + const value = typeof val2 === "string" ? val2.toLowerCase() : null; if (value !== "close" && value !== "keep-alive") { throw new InvalidArgumentError("invalid connection header"); } else if (value === "close") { @@ -5973,18 +5981,18 @@ var require_request = __commonJS({ } else if (tokenRegExp.exec(key) === null) { throw new InvalidArgumentError("invalid header key"); } else { - if (Array.isArray(val)) { - for (let i = 0; i < val.length; i++) { + if (Array.isArray(val2)) { + for (let i = 0; i < val2.length; i++) { if (skipAppend) { - if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`; - else request.headers[key] = processHeaderValue(key, val[i], skipAppend); + if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val2[i], skipAppend)}`; + else request.headers[key] = processHeaderValue(key, val2[i], skipAppend); } else { - request.headers += processHeaderValue(key, val[i]); + request.headers += processHeaderValue(key, val2[i]); } } } else { - if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend); - else request.headers += processHeaderValue(key, val); + if (skipAppend) request.headers[key] = processHeaderValue(key, val2, skipAppend); + else request.headers += processHeaderValue(key, val2); } } } @@ -10746,7 +10754,7 @@ var require_mock_interceptor = __commonJS({ var require_mock_client = __commonJS({ "node_modules/undici/lib/mock/mock-client.js"(exports2, module2) { "use strict"; - var { promisify } = require("util"); + var { promisify: promisify2 } = require("util"); var Client = require_client(); var { buildMockDispatch } = require_mock_utils(); var { @@ -10786,7 +10794,7 @@ var require_mock_client = __commonJS({ return new MockInterceptor(opts, this[kDispatches]); } async [kClose]() { - await promisify(this[kOriginalClose])(); + await promisify2(this[kOriginalClose])(); this[kConnected] = 0; this[kMockAgent][Symbols.kClients].delete(this[kOrigin]); } @@ -10799,7 +10807,7 @@ var require_mock_client = __commonJS({ var require_mock_pool = __commonJS({ "node_modules/undici/lib/mock/mock-pool.js"(exports2, module2) { "use strict"; - var { promisify } = require("util"); + var { promisify: promisify2 } = require("util"); var Pool = require_pool(); var { buildMockDispatch } = require_mock_utils(); var { @@ -10839,7 +10847,7 @@ var require_mock_pool = __commonJS({ return new MockInterceptor(opts, this[kDispatches]); } async [kClose]() { - await promisify(this[kOriginalClose])(); + await promisify2(this[kOriginalClose])(); this[kConnected] = 0; this[kMockAgent][Symbols.kClients].delete(this[kOrigin]); } @@ -11954,13 +11962,13 @@ var require_response = __commonJS({ } = require_constants2(); var { kState, kHeaders, kGuard, kRealm } = require_symbols2(); var { webidl } = require_webidl(); - var { FormData } = require_formdata(); + var { FormData: FormData2 } = require_formdata(); var { getGlobalOrigin } = require_global(); var { URLSerializer } = require_dataURL(); var { kHeadersList, kConstruct } = require_symbols(); var assert = require("assert"); var { types } = require("util"); - var ReadableStream = globalThis.ReadableStream || require("stream/web").ReadableStream; + var ReadableStream2 = globalThis.ReadableStream || require("stream/web").ReadableStream; var textEncoder = new TextEncoder("utf-8"); var Response = class _Response { // Creates network error Response. @@ -12247,10 +12255,10 @@ var require_response = __commonJS({ } } webidl.converters.ReadableStream = webidl.interfaceConverter( - ReadableStream + ReadableStream2 ); webidl.converters.FormData = webidl.interfaceConverter( - FormData + FormData2 ); webidl.converters.URLSearchParams = webidl.interfaceConverter( URLSearchParams @@ -12274,7 +12282,7 @@ var require_response = __commonJS({ return webidl.converters.DOMString(V); }; webidl.converters.BodyInit = function(V) { - if (V instanceof ReadableStream) { + if (V instanceof ReadableStream2) { return webidl.converters.ReadableStream(V); } if (V?.[Symbol.asyncIterator]) { @@ -12575,8 +12583,8 @@ var require_request2 = __commonJS({ const headers = init.headers !== void 0 ? init.headers : new HeadersList(headersList); headersList.clear(); if (headers instanceof HeadersList) { - for (const [key, val] of headers) { - headersList.append(key, val); + for (const [key, val2] of headers) { + headersList.append(key, val2); } headersList.cookies = headers.cookies; } else { @@ -13014,7 +13022,7 @@ var require_fetch = __commonJS({ var { STATUS_CODES } = require("http"); var GET_OR_HEAD = ["GET", "HEAD"]; var resolveObjectURL; - var ReadableStream = globalThis.ReadableStream; + var ReadableStream2 = globalThis.ReadableStream; var Fetch = class extends EE { constructor(dispatcher) { super(); @@ -13761,10 +13769,10 @@ var require_fetch = __commonJS({ const cancelAlgorithm = (reason) => { fetchParams.controller.abort(reason); }; - if (!ReadableStream) { - ReadableStream = require("stream/web").ReadableStream; + if (!ReadableStream2) { + ReadableStream2 = require("stream/web").ReadableStream; } - const stream = new ReadableStream( + const stream = new ReadableStream2( { async start(controller) { fetchParams.controller.controller = controller; @@ -13876,24 +13884,24 @@ var require_fetch = __commonJS({ if (Array.isArray(headersList)) { for (let n = 0; n < headersList.length; n += 2) { const key = headersList[n + 0].toString("latin1"); - const val = headersList[n + 1].toString("latin1"); + const val2 = headersList[n + 1].toString("latin1"); if (key.toLowerCase() === "content-encoding") { - codings = val.toLowerCase().split(",").map((x) => x.trim()); + codings = val2.toLowerCase().split(",").map((x) => x.trim()); } else if (key.toLowerCase() === "location") { - location = val; + location = val2; } - headers[kHeadersList].append(key, val); + headers[kHeadersList].append(key, val2); } } else { const keys = Object.keys(headersList); for (const key of keys) { - const val = headersList[key]; + const val2 = headersList[key]; if (key.toLowerCase() === "content-encoding") { - codings = val.toLowerCase().split(",").map((x) => x.trim()).reverse(); + codings = val2.toLowerCase().split(",").map((x) => x.trim()).reverse(); } else if (key.toLowerCase() === "location") { - location = val; + location = val2; } - headers[kHeadersList].append(key, val); + headers[kHeadersList].append(key, val2); } } this.body = new Readable({ read: resume }); @@ -13960,8 +13968,8 @@ var require_fetch = __commonJS({ const headers = new Headers(); for (let n = 0; n < headersList.length; n += 2) { const key = headersList[n + 0].toString("latin1"); - const val = headersList[n + 1].toString("latin1"); - headers[kHeadersList].append(key, val); + const val2 = headersList[n + 1].toString("latin1"); + headers[kHeadersList].append(key, val2); } resolve2({ status, @@ -14370,7 +14378,7 @@ var require_util4 = __commonJS({ var { serializeAMimeType, parseMIMEType } = require_dataURL(); var { types } = require("util"); var { StringDecoder } = require("string_decoder"); - var { btoa } = require("buffer"); + var { btoa: btoa2 } = require("buffer"); var staticPropertyDescriptors = { enumerable: true, writable: false, @@ -14462,9 +14470,9 @@ var require_util4 = __commonJS({ dataURL += ";base64,"; const decoder = new StringDecoder("latin1"); for (const chunk of bytes) { - dataURL += btoa(decoder.write(chunk)); + dataURL += btoa2(decoder.write(chunk)); } - dataURL += btoa(decoder.end()); + dataURL += btoa2(decoder.end()); return dataURL; } case "Text": { @@ -17288,7 +17296,7 @@ var require_undici = __commonJS({ var require_lib = __commonJS({ "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -17301,21 +17309,21 @@ var require_lib = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -17344,10 +17352,10 @@ var require_lib = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; - var http = __importStar(require("http")); - var https = __importStar(require("https")); - var pm = __importStar(require_proxy()); - var tunnel = __importStar(require_tunnel2()); + var http = __importStar4(require("http")); + var https = __importStar4(require("https")); + var pm = __importStar4(require_proxy()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); var HttpCodes; (function(HttpCodes2) { @@ -17422,8 +17430,8 @@ var require_lib = __commonJS({ this.message = message; } readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve2) => __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { let output = Buffer.alloc(0); this.message.on("data", (chunk) => { output = Buffer.concat([output, chunk]); @@ -17435,8 +17443,8 @@ var require_lib = __commonJS({ }); } readBodyBuffer() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve2) => __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { const chunks = []; this.message.on("data", (chunk) => { chunks.push(chunk); @@ -17493,42 +17501,42 @@ var require_lib = __commonJS({ } } options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); }); } get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("GET", requestUrl, null, additionalHeaders || {}); }); } del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("DELETE", requestUrl, null, additionalHeaders || {}); }); } post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("POST", requestUrl, data, additionalHeaders || {}); }); } patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("PATCH", requestUrl, data, additionalHeaders || {}); }); } put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("PUT", requestUrl, data, additionalHeaders || {}); }); } head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("HEAD", requestUrl, null, additionalHeaders || {}); }); } sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request(verb, requestUrl, stream, additionalHeaders); }); } @@ -17537,14 +17545,14 @@ var require_lib = __commonJS({ * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); const res = yield this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); @@ -17553,7 +17561,7 @@ var require_lib = __commonJS({ }); } putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); @@ -17562,7 +17570,7 @@ var require_lib = __commonJS({ }); } patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); @@ -17576,17 +17584,17 @@ var require_lib = __commonJS({ * Prefer get, del, post and patch */ request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (this._disposed) { throw new Error("Client has already been disposed."); } const parsedUrl = new URL(requestUrl); - let info3 = this._prepareRequest(verb, parsedUrl, headers); + let info4 = this._prepareRequest(verb, parsedUrl, headers); const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; let numTries = 0; let response; do { - response = yield this.requestRaw(info3, data); + response = yield this.requestRaw(info4, data); if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (const handler of this.handlers) { @@ -17596,7 +17604,7 @@ var require_lib = __commonJS({ } } if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info3, data); + return authenticationHandler.handleAuthentication(this, info4, data); } else { return response; } @@ -17619,8 +17627,8 @@ var require_lib = __commonJS({ } } } - info3 = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info3, data); + info4 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info4, data); redirectsRemaining--; } if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { @@ -17649,8 +17657,8 @@ var require_lib = __commonJS({ * @param info * @param data */ - requestRaw(info3, data) { - return __awaiter(this, void 0, void 0, function* () { + requestRaw(info4, data) { + return __awaiter4(this, void 0, void 0, function* () { return new Promise((resolve2, reject) => { function callbackForResult(err, res) { if (err) { @@ -17661,7 +17669,7 @@ var require_lib = __commonJS({ resolve2(res); } } - this.requestRawWithCallback(info3, data, callbackForResult); + this.requestRawWithCallback(info4, data, callbackForResult); }); }); } @@ -17671,12 +17679,12 @@ var require_lib = __commonJS({ * @param data * @param onResult */ - requestRawWithCallback(info3, data, onResult) { + requestRawWithCallback(info4, data, onResult) { if (typeof data === "string") { - if (!info3.options.headers) { - info3.options.headers = {}; + if (!info4.options.headers) { + info4.options.headers = {}; } - info3.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + info4.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } let callbackCalled = false; function handleResult(err, res) { @@ -17685,7 +17693,7 @@ var require_lib = __commonJS({ onResult(err, res); } } - const req = info3.httpModule.request(info3.options, (msg) => { + const req = info4.httpModule.request(info4.options, (msg) => { const res = new HttpClientResponse(msg); handleResult(void 0, res); }); @@ -17697,7 +17705,7 @@ var require_lib = __commonJS({ if (socket) { socket.end(); } - handleResult(new Error(`Request timeout: ${info3.options.path}`)); + handleResult(new Error(`Request timeout: ${info4.options.path}`)); }); req.on("error", function(err) { handleResult(err); @@ -17733,27 +17741,27 @@ var require_lib = __commonJS({ return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } _prepareRequest(method, requestUrl, headers) { - const info3 = {}; - info3.parsedUrl = requestUrl; - const usingSsl = info3.parsedUrl.protocol === "https:"; - info3.httpModule = usingSsl ? https : http; + const info4 = {}; + info4.parsedUrl = requestUrl; + const usingSsl = info4.parsedUrl.protocol === "https:"; + info4.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; - info3.options = {}; - info3.options.host = info3.parsedUrl.hostname; - info3.options.port = info3.parsedUrl.port ? parseInt(info3.parsedUrl.port) : defaultPort; - info3.options.path = (info3.parsedUrl.pathname || "") + (info3.parsedUrl.search || ""); - info3.options.method = method; - info3.options.headers = this._mergeHeaders(headers); + info4.options = {}; + info4.options.host = info4.parsedUrl.hostname; + info4.options.port = info4.parsedUrl.port ? parseInt(info4.parsedUrl.port) : defaultPort; + info4.options.path = (info4.parsedUrl.pathname || "") + (info4.parsedUrl.search || ""); + info4.options.method = method; + info4.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { - info3.options.headers["user-agent"] = this.userAgent; + info4.options.headers["user-agent"] = this.userAgent; } - info3.options.agent = this._getAgent(info3.parsedUrl); + info4.options.agent = this._getAgent(info4.parsedUrl); if (this.handlers) { for (const handler of this.handlers) { - handler.prepareRequest(info3.options); + handler.prepareRequest(info4.options); } } - return info3; + return info4; } _mergeHeaders(headers) { if (this.requestOptions && this.requestOptions.headers) { @@ -17837,15 +17845,15 @@ var require_lib = __commonJS({ return proxyAgent; } _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); }); } _processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve2, reject) => __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, @@ -17907,7 +17915,7 @@ var require_lib = __commonJS({ var require_auth = __commonJS({ "node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -17952,7 +17960,7 @@ var require_auth = __commonJS({ return false; } handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { throw new Error("not implemented"); }); } @@ -17975,7 +17983,7 @@ var require_auth = __commonJS({ return false; } handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { throw new Error("not implemented"); }); } @@ -17998,7 +18006,7 @@ var require_auth = __commonJS({ return false; } handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { throw new Error("not implemented"); }); } @@ -18011,7 +18019,7 @@ var require_auth = __commonJS({ var require_oidc_utils = __commonJS({ "node_modules/@actions/core/lib/oidc-utils.js"(exports2) { "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -18067,7 +18075,7 @@ var require_oidc_utils = __commonJS({ } static getCall(id_token_url) { var _a; - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const httpclient = _OidcClient.createHttpClient(); const res = yield httpclient.getJson(id_token_url).catch((error2) => { throw new Error(`Failed to get ID Token. @@ -18084,7 +18092,7 @@ var require_oidc_utils = __commonJS({ }); } static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { try { let id_token_url = _OidcClient.getIDTokenUrl(); if (audience) { @@ -18109,7 +18117,7 @@ var require_oidc_utils = __commonJS({ var require_summary = __commonJS({ "node_modules/@actions/core/lib/summary.js"(exports2) { "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -18140,7 +18148,7 @@ var require_summary = __commonJS({ exports2.summary = exports2.markdownSummary = exports2.SUMMARY_DOCS_URL = exports2.SUMMARY_ENV_VAR = void 0; var os_1 = require("os"); var fs_1 = require("fs"); - var { access, appendFile, writeFile } = fs_1.promises; + var { access: access2, appendFile, writeFile } = fs_1.promises; exports2.SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; exports2.SUMMARY_DOCS_URL = "https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary"; var Summary = class { @@ -18154,7 +18162,7 @@ var require_summary = __commonJS({ * @returns step summary file path */ filePath() { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (this._filePath) { return this._filePath; } @@ -18163,7 +18171,7 @@ var require_summary = __commonJS({ throw new Error(`Unable to find environment variable for $${exports2.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); } try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + yield access2(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); } catch (_a) { throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); } @@ -18195,7 +18203,7 @@ var require_summary = __commonJS({ * @returns {Promise} summary instance */ write(options) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); const filePath = yield this.filePath(); const writeFunc = overwrite ? writeFile : appendFile; @@ -18209,7 +18217,7 @@ var require_summary = __commonJS({ * @returns {Summary} summary instance */ clear() { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.emptyBuffer().write({ overwrite: true }); }); } @@ -18403,7 +18411,7 @@ var require_summary = __commonJS({ var require_path_utils = __commonJS({ "node_modules/@actions/core/lib/path-utils.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -18416,23 +18424,23 @@ var require_path_utils = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.toPlatformPath = exports2.toWin32Path = exports2.toPosixPath = void 0; - var path2 = __importStar(require("path")); + var path2 = __importStar4(require("path")); function toPosixPath(pth) { return pth.replace(/[\\]/g, "/"); } @@ -18452,7 +18460,7 @@ var require_path_utils = __commonJS({ var require_io_util = __commonJS({ "node_modules/@actions/io/lib/io-util.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; @@ -18461,21 +18469,21 @@ var require_io_util = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -18505,14 +18513,14 @@ var require_io_util = __commonJS({ var _a; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getCmdPath = exports2.tryGetExecutablePath = exports2.isRooted = exports2.isDirectory = exports2.exists = exports2.READONLY = exports2.UV_FS_O_EXLOCK = exports2.IS_WINDOWS = exports2.unlink = exports2.symlink = exports2.stat = exports2.rmdir = exports2.rm = exports2.rename = exports2.readlink = exports2.readdir = exports2.open = exports2.mkdir = exports2.lstat = exports2.copyFile = exports2.chmod = void 0; - var fs = __importStar(require("fs")); - var path2 = __importStar(require("path")); + var fs = __importStar4(require("fs")); + var path2 = __importStar4(require("path")); _a = fs.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.readlink = _a.readlink, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; exports2.IS_WINDOWS = process.platform === "win32"; exports2.UV_FS_O_EXLOCK = 268435456; exports2.READONLY = fs.constants.O_RDONLY; function exists(fsPath) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { try { yield exports2.stat(fsPath); } catch (err) { @@ -18526,7 +18534,7 @@ var require_io_util = __commonJS({ } exports2.exists = exists; function isDirectory(fsPath, useStat = false) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const stats = useStat ? yield exports2.stat(fsPath) : yield exports2.lstat(fsPath); return stats.isDirectory(); }); @@ -18544,7 +18552,7 @@ var require_io_util = __commonJS({ } exports2.isRooted = isRooted; function tryGetExecutablePath(filePath, extensions) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { let stats = void 0; try { stats = yield exports2.stat(filePath); @@ -18625,7 +18633,7 @@ var require_io_util = __commonJS({ var require_io = __commonJS({ "node_modules/@actions/io/lib/io.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; @@ -18634,21 +18642,21 @@ var require_io = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -18678,10 +18686,10 @@ var require_io = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.findInPath = exports2.which = exports2.mkdirP = exports2.rmRF = exports2.mv = exports2.cp = void 0; var assert_1 = require("assert"); - var path2 = __importStar(require("path")); - var ioUtil = __importStar(require_io_util()); + var path2 = __importStar4(require("path")); + var ioUtil = __importStar4(require_io_util()); function cp(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const { force, recursive, copySourceDirectory } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; if (destStat && destStat.isFile() && !force) { @@ -18708,7 +18716,7 @@ var require_io = __commonJS({ } exports2.cp = cp; function mv(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { @@ -18729,7 +18737,7 @@ var require_io = __commonJS({ } exports2.mv = mv; function rmRF(inputPath) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { if (/[*"<>|]/.test(inputPath)) { throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); @@ -18749,19 +18757,19 @@ var require_io = __commonJS({ } exports2.rmRF = rmRF; function mkdirP(fsPath) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { assert_1.ok(fsPath, "a path argument must be provided"); yield ioUtil.mkdir(fsPath, { recursive: true }); }); } exports2.mkdirP = mkdirP; - function which3(tool, check) { - return __awaiter(this, void 0, void 0, function* () { + function which4(tool, check) { + return __awaiter4(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } if (check) { - const result = yield which3(tool, false); + const result = yield which4(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); @@ -18778,9 +18786,9 @@ var require_io = __commonJS({ return ""; }); } - exports2.which = which3; + exports2.which = which4; function findInPath(tool) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } @@ -18828,7 +18836,7 @@ var require_io = __commonJS({ return { force, recursive, copySourceDirectory }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (currentDepth >= 255) return; currentDepth++; @@ -18848,7 +18856,7 @@ var require_io = __commonJS({ }); } function copyFile(srcFile, destFile, force) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { try { yield ioUtil.lstat(destFile); @@ -18873,7 +18881,7 @@ var require_io = __commonJS({ var require_toolrunner = __commonJS({ "node_modules/@actions/exec/lib/toolrunner.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; @@ -18882,21 +18890,21 @@ var require_toolrunner = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -18925,15 +18933,15 @@ var require_toolrunner = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.argStringToArray = exports2.ToolRunner = void 0; - var os = __importStar(require("os")); - var events = __importStar(require("events")); - var child = __importStar(require("child_process")); - var path2 = __importStar(require("path")); - var io3 = __importStar(require_io()); - var ioUtil = __importStar(require_io_util()); + var os2 = __importStar4(require("os")); + var events = __importStar4(require("events")); + var child = __importStar4(require("child_process")); + var path2 = __importStar4(require("path")); + var io4 = __importStar4(require_io()); + var ioUtil = __importStar4(require_io_util()); var timers_1 = require("timers"); var IS_WINDOWS = process.platform === "win32"; - var ToolRunner2 = class extends events.EventEmitter { + var ToolRunner3 = class extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { @@ -18980,12 +18988,12 @@ var require_toolrunner = __commonJS({ _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); - let n = s.indexOf(os.EOL); + let n = s.indexOf(os2.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); + s = s.substring(n + os2.EOL.length); + n = s.indexOf(os2.EOL); } return s; } catch (err) { @@ -19141,12 +19149,12 @@ var require_toolrunner = __commonJS({ * @returns number */ exec() { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { this.toolPath = path2.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } - this.toolPath = yield io3.which(this.toolPath, true); - return new Promise((resolve2, reject) => __awaiter(this, void 0, void 0, function* () { + this.toolPath = yield io4.which(this.toolPath, true); + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { this._debug(`exec tool: ${this.toolPath}`); this._debug("arguments:"); for (const arg of this.args) { @@ -19154,7 +19162,7 @@ var require_toolrunner = __commonJS({ } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os2.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on("debug", (message) => { @@ -19242,7 +19250,7 @@ var require_toolrunner = __commonJS({ }); } }; - exports2.ToolRunner = ToolRunner2; + exports2.ToolRunner = ToolRunner3; function argStringToArray(argString) { const args = []; let inQuotes = false; @@ -19357,7 +19365,7 @@ var require_toolrunner = __commonJS({ var require_exec = __commonJS({ "node_modules/@actions/exec/lib/exec.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; @@ -19366,21 +19374,21 @@ var require_exec = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -19410,9 +19418,9 @@ var require_exec = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getExecOutput = exports2.exec = void 0; var string_decoder_1 = require("string_decoder"); - var tr = __importStar(require_toolrunner()); + var tr = __importStar4(require_toolrunner()); function exec2(commandLine, args, options) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const commandArgs = tr.argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); @@ -19426,7 +19434,7 @@ var require_exec = __commonJS({ exports2.exec = exec2; function getExecOutput2(commandLine, args, options) { var _a, _b; - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { let stdout = ""; let stderr = ""; const stdoutDecoder = new string_decoder_1.StringDecoder("utf8"); @@ -19464,7 +19472,7 @@ var require_exec = __commonJS({ var require_platform = __commonJS({ "node_modules/@actions/core/lib/platform.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -19477,21 +19485,21 @@ var require_platform = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -19518,14 +19526,14 @@ var require_platform = __commonJS({ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getDetails = exports2.isLinux = exports2.isMacOS = exports2.isWindows = exports2.arch = exports2.platform = void 0; - var os_1 = __importDefault(require("os")); - var exec2 = __importStar(require_exec()); - var getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var os_1 = __importDefault4(require("os")); + var exec2 = __importStar4(require_exec()); + var getWindowsInfo = () => __awaiter4(void 0, void 0, void 0, function* () { const { stdout: version } = yield exec2.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', void 0, { silent: true }); @@ -19537,7 +19545,7 @@ var require_platform = __commonJS({ version: version.trim() }; }); - var getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var getMacOsInfo = () => __awaiter4(void 0, void 0, void 0, function* () { var _a, _b, _c, _d; const { stdout } = yield exec2.getExecOutput("sw_vers", void 0, { silent: true @@ -19549,7 +19557,7 @@ var require_platform = __commonJS({ version }; }); - var getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var getLinuxInfo = () => __awaiter4(void 0, void 0, void 0, function* () { const { stdout } = yield exec2.getExecOutput("lsb_release", ["-i", "-r", "-s"], { silent: true }); @@ -19565,7 +19573,7 @@ var require_platform = __commonJS({ exports2.isMacOS = exports2.platform === "darwin"; exports2.isLinux = exports2.platform === "linux"; function getDetails() { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return Object.assign(Object.assign({}, yield exports2.isWindows ? getWindowsInfo() : exports2.isMacOS ? getMacOsInfo() : getLinuxInfo()), { platform: exports2.platform, arch: exports2.arch, @@ -19583,7 +19591,7 @@ var require_platform = __commonJS({ var require_core = __commonJS({ "node_modules/@actions/core/lib/core.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -19596,21 +19604,21 @@ var require_core = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -19642,24 +19650,24 @@ var require_core = __commonJS({ var command_1 = require_command(); var file_command_1 = require_file_command(); var utils_1 = require_utils(); - var os = __importStar(require("os")); - var path2 = __importStar(require("path")); + var os2 = __importStar4(require("os")); + var path2 = __importStar4(require("path")); var oidc_utils_1 = require_oidc_utils(); var ExitCode; (function(ExitCode2) { ExitCode2[ExitCode2["Success"] = 0] = "Success"; ExitCode2[ExitCode2["Failure"] = 1] = "Failure"; })(ExitCode || (exports2.ExitCode = ExitCode = {})); - function exportVariable3(name, val) { - const convertedVal = (0, utils_1.toCommandValue)(val); + function exportVariable4(name, val2) { + const convertedVal = (0, utils_1.toCommandValue)(val2); process.env[name] = convertedVal; const filePath = process.env["GITHUB_ENV"] || ""; if (filePath) { - return (0, file_command_1.issueFileCommand)("ENV", (0, file_command_1.prepareKeyValueMessage)(name, val)); + return (0, file_command_1.issueFileCommand)("ENV", (0, file_command_1.prepareKeyValueMessage)(name, val2)); } (0, command_1.issueCommand)("set-env", { name }, convertedVal); } - exports2.exportVariable = exportVariable3; + exports2.exportVariable = exportVariable4; function setSecret2(secret) { (0, command_1.issueCommand)("add-mask", {}, secret); } @@ -19675,14 +19683,14 @@ var require_core = __commonJS({ } exports2.addPath = addPath; function getInput2(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || ""; - if (options && options.required && !val) { + const val2 = process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || ""; + if (options && options.required && !val2) { throw new Error(`Input required and not supplied: ${name}`); } if (options && options.trimWhitespace === false) { - return val; + return val2; } - return val.trim(); + return val2.trim(); } exports2.getInput = getInput2; function getMultilineInput(name, options) { @@ -19696,10 +19704,10 @@ var require_core = __commonJS({ function getBooleanInput(name, options) { const trueValue = ["true", "True", "TRUE"]; const falseValue = ["false", "False", "FALSE"]; - const val = getInput2(name, options); - if (trueValue.includes(val)) + const val2 = getInput2(name, options); + if (trueValue.includes(val2)) return true; - if (falseValue.includes(val)) + if (falseValue.includes(val2)) return false; throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name} Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); @@ -19710,7 +19718,7 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); if (filePath) { return (0, file_command_1.issueFileCommand)("OUTPUT", (0, file_command_1.prepareKeyValueMessage)(name, value)); } - process.stdout.write(os.EOL); + process.stdout.write(os2.EOL); (0, command_1.issueCommand)("set-output", { name }, (0, utils_1.toCommandValue)(value)); } exports2.setOutput = setOutput2; @@ -19727,26 +19735,26 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); return process.env["RUNNER_DEBUG"] === "1"; } exports2.isDebug = isDebug; - function debug(message) { + function debug3(message) { (0, command_1.issueCommand)("debug", {}, message); } - exports2.debug = debug; + exports2.debug = debug3; function error2(message, properties = {}) { (0, command_1.issueCommand)("error", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports2.error = error2; - function warning2(message, properties = {}) { + function warning4(message, properties = {}) { (0, command_1.issueCommand)("warning", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } - exports2.warning = warning2; + exports2.warning = warning4; function notice(message, properties = {}) { (0, command_1.issueCommand)("notice", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports2.notice = notice; - function info3(message) { - process.stdout.write(message + os.EOL); + function info4(message) { + process.stdout.write(message + os2.EOL); } - exports2.info = info3; + exports2.info = info4; function startGroup3(name) { (0, command_1.issue)("group", name); } @@ -19756,7 +19764,7 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } exports2.endGroup = endGroup3; function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { startGroup3(name); let result; try { @@ -19781,7 +19789,7 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } exports2.getState = getState2; function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return yield oidc_utils_1.OidcClient.getIDToken(aud); }); } @@ -19804,7 +19812,7 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); Object.defineProperty(exports2, "toPlatformPath", { enumerable: true, get: function() { return path_utils_1.toPlatformPath; } }); - exports2.platform = __importStar(require_platform()); + exports2.platform = __importStar4(require_platform()); } }); @@ -19844,9 +19852,9 @@ var require_constants6 = __commonJS({ var require_debug = __commonJS({ "node_modules/semver/internal/debug.js"(exports2, module2) { "use strict"; - var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { + var debug3 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { }; - module2.exports = debug; + module2.exports = debug3; } }); @@ -19859,7 +19867,7 @@ var require_re = __commonJS({ MAX_SAFE_BUILD_LENGTH, MAX_LENGTH } = require_constants6(); - var debug = require_debug(); + var debug3 = require_debug(); exports2 = module2.exports = {}; var re = exports2.re = []; var safeRe = exports2.safeRe = []; @@ -19882,7 +19890,7 @@ var require_re = __commonJS({ var createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value); const index = R++; - debug(name, index, value); + debug3(name, index, value); t[name] = index; src[index] = value; safeSrc[index] = safe; @@ -19983,7 +19991,7 @@ var require_identifiers = __commonJS({ var require_semver = __commonJS({ "node_modules/semver/classes/semver.js"(exports2, module2) { "use strict"; - var debug = require_debug(); + var debug3 = require_debug(); var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants6(); var { safeRe: re, t } = require_re(); var parseOptions = require_parse_options(); @@ -20005,7 +20013,7 @@ var require_semver = __commonJS({ `version is longer than ${MAX_LENGTH} characters` ); } - debug("SemVer", version, options); + debug3("SemVer", version, options); this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; @@ -20053,7 +20061,7 @@ var require_semver = __commonJS({ return this.version; } compare(other) { - debug("SemVer.compare", this.version, this.options, other); + debug3("SemVer.compare", this.version, this.options, other); if (!(other instanceof _SemVer)) { if (typeof other === "string" && other === this.version) { return 0; @@ -20086,7 +20094,7 @@ var require_semver = __commonJS({ do { const a = this.prerelease[i]; const b = other.prerelease[i]; - debug("prerelease compare", i, a, b); + debug3("prerelease compare", i, a, b); if (a === void 0 && b === void 0) { return 0; } else if (b === void 0) { @@ -20108,7 +20116,7 @@ var require_semver = __commonJS({ do { const a = this.build[i]; const b = other.build[i]; - debug("build compare", i, a, b); + debug3("build compare", i, a, b); if (a === void 0 && b === void 0) { return 0; } else if (b === void 0) { @@ -20124,8 +20132,8 @@ var require_semver = __commonJS({ } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. - inc(release, identifier, identifierBase) { - if (release.startsWith("pre")) { + inc(release3, identifier, identifierBase) { + if (release3.startsWith("pre")) { if (!identifier && identifierBase === false) { throw new Error("invalid increment argument: identifier is empty"); } @@ -20136,7 +20144,7 @@ var require_semver = __commonJS({ } } } - switch (release) { + switch (release3) { case "premajor": this.prerelease.length = 0; this.patch = 0; @@ -20227,7 +20235,7 @@ var require_semver = __commonJS({ break; } default: - throw new Error(`invalid increment argument: ${release}`); + throw new Error(`invalid increment argument: ${release3}`); } this.raw = this.format(); if (this.build.length) { @@ -20267,11 +20275,11 @@ var require_valid = __commonJS({ "node_modules/semver/functions/valid.js"(exports2, module2) { "use strict"; var parse = require_parse2(); - var valid = (version, options) => { + var valid2 = (version, options) => { const v = parse(version, options); return v ? v.version : null; }; - module2.exports = valid; + module2.exports = valid2; } }); @@ -20293,7 +20301,7 @@ var require_inc = __commonJS({ "node_modules/semver/functions/inc.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); - var inc = (version, release, options, identifier, identifierBase) => { + var inc = (version, release3, options, identifier, identifierBase) => { if (typeof options === "string") { identifierBase = identifier; identifier = options; @@ -20303,7 +20311,7 @@ var require_inc = __commonJS({ return new SemVer( version instanceof SemVer ? version.version : version, options - ).inc(release, identifier, identifierBase).version; + ).inc(release3, identifier, identifierBase).version; } catch (er) { return null; } @@ -20508,8 +20516,8 @@ var require_gte = __commonJS({ "node_modules/semver/functions/gte.js"(exports2, module2) { "use strict"; var compare = require_compare(); - var gte2 = (a, b, loose) => compare(a, b, loose) >= 0; - module2.exports = gte2; + var gte3 = (a, b, loose) => compare(a, b, loose) >= 0; + module2.exports = gte3; } }); @@ -20530,7 +20538,7 @@ var require_cmp = __commonJS({ var eq = require_eq(); var neq = require_neq(); var gt = require_gt(); - var gte2 = require_gte(); + var gte3 = require_gte(); var lt = require_lt(); var lte = require_lte(); var cmp = (a, op, b, loose) => { @@ -20560,7 +20568,7 @@ var require_cmp = __commonJS({ case ">": return gt(a, b, loose); case ">=": - return gte2(a, b, loose); + return gte3(a, b, loose); case "<": return lt(a, b, loose); case "<=": @@ -20662,7 +20670,7 @@ var require_range = __commonJS({ "node_modules/semver/classes/range.js"(exports2, module2) { "use strict"; var SPACE_CHARACTERS = /\s+/g; - var Range = class _Range { + var Range2 = class _Range { constructor(range, options) { options = parseOptions(options); if (range instanceof _Range) { @@ -20736,21 +20744,21 @@ var require_range = __commonJS({ const loose = this.options.loose; const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug("hyphen replace", range); + debug3("hyphen replace", range); range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); - debug("comparator trim", range); + debug3("comparator trim", range); range = range.replace(re[t.TILDETRIM], tildeTrimReplace); - debug("tilde trim", range); + debug3("tilde trim", range); range = range.replace(re[t.CARETTRIM], caretTrimReplace); - debug("caret trim", range); + debug3("caret trim", range); let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); if (loose) { rangeList = rangeList.filter((comp) => { - debug("loose invalid filter", comp, this.options); + debug3("loose invalid filter", comp, this.options); return !!comp.match(re[t.COMPARATORLOOSE]); }); } - debug("range list", rangeList); + debug3("range list", rangeList); const rangeMap = /* @__PURE__ */ new Map(); const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); for (const comp of comparators) { @@ -20800,12 +20808,12 @@ var require_range = __commonJS({ return false; } }; - module2.exports = Range; + module2.exports = Range2; var LRU = require_lrucache(); var cache = new LRU(); var parseOptions = require_parse_options(); var Comparator = require_comparator(); - var debug = require_debug(); + var debug3 = require_debug(); var SemVer = require_semver(); var { safeRe: re, @@ -20830,15 +20838,15 @@ var require_range = __commonJS({ return result; }; var parseComparator = (comp, options) => { - debug("comp", comp, options); + debug3("comp", comp, options); comp = replaceCarets(comp, options); - debug("caret", comp); + debug3("caret", comp); comp = replaceTildes(comp, options); - debug("tildes", comp); + debug3("tildes", comp); comp = replaceXRanges(comp, options); - debug("xrange", comp); + debug3("xrange", comp); comp = replaceStars(comp, options); - debug("stars", comp); + debug3("stars", comp); return comp; }; var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; @@ -20848,7 +20856,7 @@ var require_range = __commonJS({ var replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; return comp.replace(r, (_, M, m, p, pr) => { - debug("tilde", comp, _, M, m, p, pr); + debug3("tilde", comp, _, M, m, p, pr); let ret; if (isX(M)) { ret = ""; @@ -20857,12 +20865,12 @@ var require_range = __commonJS({ } else if (isX(p)) { ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; } else if (pr) { - debug("replaceTilde pr", pr); + debug3("replaceTilde pr", pr); ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; } else { ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; } - debug("tilde return", ret); + debug3("tilde return", ret); return ret; }); }; @@ -20870,11 +20878,11 @@ var require_range = __commonJS({ return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" "); }; var replaceCaret = (comp, options) => { - debug("caret", comp, options); + debug3("caret", comp, options); const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; const z = options.includePrerelease ? "-0" : ""; return comp.replace(r, (_, M, m, p, pr) => { - debug("caret", comp, _, M, m, p, pr); + debug3("caret", comp, _, M, m, p, pr); let ret; if (isX(M)) { ret = ""; @@ -20887,7 +20895,7 @@ var require_range = __commonJS({ ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; } } else if (pr) { - debug("replaceCaret pr", pr); + debug3("replaceCaret pr", pr); if (M === "0") { if (m === "0") { ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; @@ -20898,7 +20906,7 @@ var require_range = __commonJS({ ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; } } else { - debug("no pr"); + debug3("no pr"); if (M === "0") { if (m === "0") { ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; @@ -20909,19 +20917,19 @@ var require_range = __commonJS({ ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; } } - debug("caret return", ret); + debug3("caret return", ret); return ret; }); }; var replaceXRanges = (comp, options) => { - debug("replaceXRanges", comp, options); + debug3("replaceXRanges", comp, options); return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" "); }; var replaceXRange = (comp, options) => { comp = comp.trim(); const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug("xRange", comp, ret, gtlt, M, m, p, pr); + debug3("xRange", comp, ret, gtlt, M, m, p, pr); const xM = isX(M); const xm = xM || isX(m); const xp = xm || isX(p); @@ -20968,16 +20976,16 @@ var require_range = __commonJS({ } else if (xp) { ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; } - debug("xRange return", ret); + debug3("xRange return", ret); return ret; }); }; var replaceStars = (comp, options) => { - debug("replaceStars", comp, options); + debug3("replaceStars", comp, options); return comp.trim().replace(re[t.STAR], ""); }; var replaceGTE0 = (comp, options) => { - debug("replaceGTE0", comp, options); + debug3("replaceGTE0", comp, options); return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); }; var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { @@ -21015,7 +21023,7 @@ var require_range = __commonJS({ } if (version.prerelease.length && !options.includePrerelease) { for (let i = 0; i < set2.length; i++) { - debug(set2[i].semver); + debug3(set2[i].semver); if (set2[i].semver === Comparator.ANY) { continue; } @@ -21052,7 +21060,7 @@ var require_comparator = __commonJS({ } } comp = comp.trim().split(/\s+/).join(" "); - debug("comparator", comp, options); + debug3("comparator", comp, options); this.options = options; this.loose = !!options.loose; this.parse(comp); @@ -21061,7 +21069,7 @@ var require_comparator = __commonJS({ } else { this.value = this.operator + this.semver.version; } - debug("comp", this); + debug3("comp", this); } parse(comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; @@ -21083,7 +21091,7 @@ var require_comparator = __commonJS({ return this.value; } test(version) { - debug("Comparator.test", version, this.options.loose); + debug3("Comparator.test", version, this.options.loose); if (this.semver === ANY || version === ANY) { return true; } @@ -21104,12 +21112,12 @@ var require_comparator = __commonJS({ if (this.value === "") { return true; } - return new Range(comp.value, options).test(this.value); + return new Range2(comp.value, options).test(this.value); } else if (comp.operator === "") { if (comp.value === "") { return true; } - return new Range(this.value, options).test(comp.semver); + return new Range2(this.value, options).test(comp.semver); } options = parseOptions(options); if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { @@ -21140,9 +21148,9 @@ var require_comparator = __commonJS({ var parseOptions = require_parse_options(); var { safeRe: re, t } = require_re(); var cmp = require_cmp(); - var debug = require_debug(); + var debug3 = require_debug(); var SemVer = require_semver(); - var Range = require_range(); + var Range2 = require_range(); } }); @@ -21150,10 +21158,10 @@ var require_comparator = __commonJS({ var require_satisfies = __commonJS({ "node_modules/semver/functions/satisfies.js"(exports2, module2) { "use strict"; - var Range = require_range(); + var Range2 = require_range(); var satisfies2 = (version, range, options) => { try { - range = new Range(range, options); + range = new Range2(range, options); } catch (er) { return false; } @@ -21167,8 +21175,8 @@ var require_satisfies = __commonJS({ var require_to_comparators = __commonJS({ "node_modules/semver/ranges/to-comparators.js"(exports2, module2) { "use strict"; - var Range = require_range(); - var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" ")); + var Range2 = require_range(); + var toComparators = (range, options) => new Range2(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" ")); module2.exports = toComparators; } }); @@ -21178,13 +21186,13 @@ var require_max_satisfying = __commonJS({ "node_modules/semver/ranges/max-satisfying.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); - var Range = require_range(); + var Range2 = require_range(); var maxSatisfying = (versions, range, options) => { let max = null; let maxSV = null; let rangeObj = null; try { - rangeObj = new Range(range, options); + rangeObj = new Range2(range, options); } catch (er) { return null; } @@ -21207,13 +21215,13 @@ var require_min_satisfying = __commonJS({ "node_modules/semver/ranges/min-satisfying.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); - var Range = require_range(); + var Range2 = require_range(); var minSatisfying = (versions, range, options) => { let min = null; let minSV = null; let rangeObj = null; try { - rangeObj = new Range(range, options); + rangeObj = new Range2(range, options); } catch (er) { return null; } @@ -21236,10 +21244,10 @@ var require_min_version = __commonJS({ "node_modules/semver/ranges/min-version.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); - var Range = require_range(); + var Range2 = require_range(); var gt = require_gt(); var minVersion = (range, loose) => { - range = new Range(range, loose); + range = new Range2(range, loose); let minver = new SemVer("0.0.0"); if (range.test(minver)) { return minver; @@ -21294,10 +21302,10 @@ var require_min_version = __commonJS({ var require_valid2 = __commonJS({ "node_modules/semver/ranges/valid.js"(exports2, module2) { "use strict"; - var Range = require_range(); + var Range2 = require_range(); var validRange = (range, options) => { try { - return new Range(range, options).range || "*"; + return new Range2(range, options).range || "*"; } catch (er) { return null; } @@ -21313,15 +21321,15 @@ var require_outside = __commonJS({ var SemVer = require_semver(); var Comparator = require_comparator(); var { ANY } = Comparator; - var Range = require_range(); + var Range2 = require_range(); var satisfies2 = require_satisfies(); var gt = require_gt(); var lt = require_lt(); var lte = require_lte(); - var gte2 = require_gte(); + var gte3 = require_gte(); var outside = (version, range, hilo, options) => { version = new SemVer(version, options); - range = new Range(range, options); + range = new Range2(range, options); let gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case ">": @@ -21333,7 +21341,7 @@ var require_outside = __commonJS({ break; case "<": gtfn = lt; - ltefn = gte2; + ltefn = gte3; ltfn = gt; comp = "<"; ecomp = "<="; @@ -21399,10 +21407,10 @@ var require_ltr = __commonJS({ var require_intersects = __commonJS({ "node_modules/semver/ranges/intersects.js"(exports2, module2) { "use strict"; - var Range = require_range(); + var Range2 = require_range(); var intersects = (r1, r2, options) => { - r1 = new Range(r1, options); - r2 = new Range(r2, options); + r1 = new Range2(r1, options); + r2 = new Range2(r2, options); return r1.intersects(r2, options); }; module2.exports = intersects; @@ -21463,7 +21471,7 @@ var require_simplify = __commonJS({ var require_subset = __commonJS({ "node_modules/semver/ranges/subset.js"(exports2, module2) { "use strict"; - var Range = require_range(); + var Range2 = require_range(); var Comparator = require_comparator(); var { ANY } = Comparator; var satisfies2 = require_satisfies(); @@ -21472,8 +21480,8 @@ var require_subset = __commonJS({ if (sub === dom) { return true; } - sub = new Range(sub, options); - dom = new Range(dom, options); + sub = new Range2(sub, options); + dom = new Range2(dom, options); let sawNonNull = false; OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { @@ -21630,7 +21638,7 @@ var require_semver2 = __commonJS({ var SemVer = require_semver(); var identifiers = require_identifiers(); var parse = require_parse2(); - var valid = require_valid(); + var valid2 = require_valid(); var clean = require_clean(); var inc = require_inc(); var diff = require_diff(); @@ -21648,12 +21656,12 @@ var require_semver2 = __commonJS({ var lt = require_lt(); var eq = require_eq(); var neq = require_neq(); - var gte2 = require_gte(); + var gte3 = require_gte(); var lte = require_lte(); var cmp = require_cmp(); var coerce2 = require_coerce(); var Comparator = require_comparator(); - var Range = require_range(); + var Range2 = require_range(); var satisfies2 = require_satisfies(); var toComparators = require_to_comparators(); var maxSatisfying = require_max_satisfying(); @@ -21668,7 +21676,7 @@ var require_semver2 = __commonJS({ var subset = require_subset(); module2.exports = { parse, - valid, + valid: valid2, clean, inc, diff, @@ -21686,12 +21694,12 @@ var require_semver2 = __commonJS({ lt, eq, neq, - gte: gte2, + gte: gte3, lte, cmp, coerce: coerce2, Comparator, - Range, + Range: Range2, satisfies: satisfies2, toComparators, maxSatisfying, @@ -21720,7 +21728,7 @@ var require_semver2 = __commonJS({ var require_manifest = __commonJS({ "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -21733,21 +21741,21 @@ var require_manifest = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -21776,21 +21784,21 @@ var require_manifest = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver2 = __importStar(require_semver2()); + var semver5 = __importStar4(require_semver2()); var core_1 = require_core(); - var os = require("os"); + var os2 = require("os"); var cp = require("child_process"); var fs = require("fs"); function _findMatch(versionSpec, stable, candidates, archFilter) { - return __awaiter(this, void 0, void 0, function* () { - const platFilter = os.platform(); + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os2.platform(); let result; let match; let file; for (const candidate of candidates) { const version = candidate.version; (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver2.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + if (semver5.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { file = candidate.files.find((item) => { (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); let chk = item.arch === archFilter && item.platform === platFilter; @@ -21799,7 +21807,7 @@ var require_manifest = __commonJS({ if (osVersion === item.platform_version) { chk = true; } else { - chk = semver2.satisfies(osVersion, item.platform_version); + chk = semver5.satisfies(osVersion, item.platform_version); } } return chk; @@ -21820,7 +21828,7 @@ var require_manifest = __commonJS({ } exports2._findMatch = _findMatch; function _getOsVersion() { - const plat = os.platform(); + const plat = os2.platform(); let version = ""; if (plat === "darwin") { version = cp.execSync("sw_vers -productVersion").toString(); @@ -21859,7 +21867,7 @@ var require_manifest = __commonJS({ var require_retry_helper = __commonJS({ "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -21872,21 +21880,21 @@ var require_retry_helper = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -21915,7 +21923,7 @@ var require_retry_helper = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RetryHelper = void 0; - var core9 = __importStar(require_core()); + var core12 = __importStar4(require_core()); var RetryHelper = class { constructor(maxAttempts, minSeconds, maxSeconds) { if (maxAttempts < 1) { @@ -21929,7 +21937,7 @@ var require_retry_helper = __commonJS({ } } execute(action, isRetryable) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { let attempt = 1; while (attempt < this.maxAttempts) { try { @@ -21938,10 +21946,10 @@ var require_retry_helper = __commonJS({ if (isRetryable && !isRetryable(err)) { throw err; } - core9.info(err.message); + core12.info(err.message); } const seconds = this.getSleepAmount(); - core9.info(`Waiting ${seconds} seconds before trying again`); + core12.info(`Waiting ${seconds} seconds before trying again`); yield this.sleep(seconds); attempt++; } @@ -21952,7 +21960,7 @@ var require_retry_helper = __commonJS({ return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; } sleep(seconds) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return new Promise((resolve2) => setTimeout(resolve2, seconds * 1e3)); }); } @@ -21965,7 +21973,7 @@ var require_retry_helper = __commonJS({ var require_tool_cache = __commonJS({ "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -21978,21 +21986,21 @@ var require_tool_cache = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -22021,17 +22029,17 @@ var require_tool_cache = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core9 = __importStar(require_core()); - var io3 = __importStar(require_io()); - var crypto = __importStar(require("crypto")); - var fs = __importStar(require("fs")); - var mm = __importStar(require_manifest()); - var os = __importStar(require("os")); - var path2 = __importStar(require("path")); - var httpm = __importStar(require_lib()); - var semver2 = __importStar(require_semver2()); - var stream = __importStar(require("stream")); - var util = __importStar(require("util")); + var core12 = __importStar4(require_core()); + var io4 = __importStar4(require_io()); + var crypto = __importStar4(require("crypto")); + var fs = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os2 = __importStar4(require("os")); + var path2 = __importStar4(require("path")); + var httpm = __importStar4(require_lib()); + var semver5 = __importStar4(require_semver2()); + var stream = __importStar4(require("stream")); + var util = __importStar4(require("util")); var assert_1 = require("assert"); var exec_1 = require_exec(); var retry_helper_1 = require_retry_helper(); @@ -22047,16 +22055,16 @@ var require_tool_cache = __commonJS({ var IS_MAC = process.platform === "darwin"; var userAgent = "actions/tool-cache"; function downloadTool2(url, dest, auth, headers) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { dest = dest || path2.join(_getTempDirectory(), crypto.randomUUID()); - yield io3.mkdirP(path2.dirname(dest)); - core9.debug(`Downloading ${url}`); - core9.debug(`Destination ${dest}`); + yield io4.mkdirP(path2.dirname(dest)); + core12.debug(`Downloading ${url}`); + core12.debug(`Destination ${dest}`); const maxAttempts = 3; const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { return yield downloadToolAttempt(url, dest || "", auth, headers); }), (err) => { if (err instanceof HTTPError && err.httpStatusCode) { @@ -22070,7 +22078,7 @@ var require_tool_cache = __commonJS({ } exports2.downloadTool = downloadTool2; function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (fs.existsSync(dest)) { throw new Error(`Destination file path ${dest} already exists`); } @@ -22078,7 +22086,7 @@ var require_tool_cache = __commonJS({ allowRetries: false }); if (auth) { - core9.debug("set auth"); + core12.debug("set auth"); if (headers === void 0) { headers = {}; } @@ -22087,7 +22095,7 @@ var require_tool_cache = __commonJS({ const response = yield http.get(url, headers); if (response.message.statusCode !== 200) { const err = new HTTPError(response.message.statusCode); - core9.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + core12.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); throw err; } const pipeline = util.promisify(stream.pipeline); @@ -22096,23 +22104,23 @@ var require_tool_cache = __commonJS({ let succeeded = false; try { yield pipeline(readStream, fs.createWriteStream(dest)); - core9.debug("download complete"); + core12.debug("download complete"); succeeded = true; return dest; } finally { if (!succeeded) { - core9.debug("download failed"); + core12.debug("download failed"); try { - yield io3.rmRF(dest); + yield io4.rmRF(dest); } catch (err) { - core9.debug(`Failed to delete '${dest}'. ${err.message}`); + core12.debug(`Failed to delete '${dest}'. ${err.message}`); } } } }); } function extract7z(file, dest, _7zPath) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); (0, assert_1.ok)(file, 'parameter "file" is required'); dest = yield _createExtractFolder(dest); @@ -22120,7 +22128,7 @@ var require_tool_cache = __commonJS({ process.chdir(dest); if (_7zPath) { try { - const logLevel = core9.isDebug() ? "-bb1" : "-bb0"; + const logLevel = core12.isDebug() ? "-bb1" : "-bb0"; const args = [ "x", logLevel, @@ -22154,7 +22162,7 @@ var require_tool_cache = __commonJS({ silent: true }; try { - const powershellPath = yield io3.which("powershell", true); + const powershellPath = yield io4.which("powershell", true); yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); } finally { process.chdir(originalCwd); @@ -22165,12 +22173,12 @@ var require_tool_cache = __commonJS({ } exports2.extract7z = extract7z; function extractTar2(file, dest, flags = "xz") { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } dest = yield _createExtractFolder(dest); - core9.debug("Checking tar --version"); + core12.debug("Checking tar --version"); let versionOutput = ""; yield (0, exec_1.exec)("tar --version", [], { ignoreReturnCode: true, @@ -22180,7 +22188,7 @@ var require_tool_cache = __commonJS({ stderr: (data) => versionOutput += data.toString() } }); - core9.debug(versionOutput.trim()); + core12.debug(versionOutput.trim()); const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); let args; if (flags instanceof Array) { @@ -22188,7 +22196,7 @@ var require_tool_cache = __commonJS({ } else { args = [flags]; } - if (core9.isDebug() && !flags.includes("v")) { + if (core12.isDebug() && !flags.includes("v")) { args.push("-v"); } let destArg = dest; @@ -22209,7 +22217,7 @@ var require_tool_cache = __commonJS({ } exports2.extractTar = extractTar2; function extractXar(file, dest, flags = []) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); (0, assert_1.ok)(file, 'parameter "file" is required'); dest = yield _createExtractFolder(dest); @@ -22220,17 +22228,17 @@ var require_tool_cache = __commonJS({ args = [flags]; } args.push("-x", "-C", dest, "-f", file); - if (core9.isDebug()) { + if (core12.isDebug()) { args.push("-v"); } - const xarPath = yield io3.which("xar", true); + const xarPath = yield io4.which("xar", true); yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); return dest; }); } exports2.extractXar = extractXar; function extractZip(file, dest) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } @@ -22245,10 +22253,10 @@ var require_tool_cache = __commonJS({ } exports2.extractZip = extractZip; function extractZipWin(file, dest) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io3.which("pwsh", false); + const pwshPath = yield io4.which("pwsh", false); if (pwshPath) { const pwshCommand = [ `$ErrorActionPreference = 'Stop' ;`, @@ -22265,7 +22273,7 @@ var require_tool_cache = __commonJS({ "-Command", pwshCommand ]; - core9.debug(`Using pwsh at path: ${pwshPath}`); + core12.debug(`Using pwsh at path: ${pwshPath}`); yield (0, exec_1.exec)(`"${pwshPath}"`, args); } else { const powershellCommand = [ @@ -22284,17 +22292,17 @@ var require_tool_cache = __commonJS({ "-Command", powershellCommand ]; - const powershellPath = yield io3.which("powershell", true); - core9.debug(`Using powershell at path: ${powershellPath}`); + const powershellPath = yield io4.which("powershell", true); + core12.debug(`Using powershell at path: ${powershellPath}`); yield (0, exec_1.exec)(`"${powershellPath}"`, args); } }); } function extractZipNix(file, dest) { - return __awaiter(this, void 0, void 0, function* () { - const unzipPath = yield io3.which("unzip", true); + return __awaiter4(this, void 0, void 0, function* () { + const unzipPath = yield io4.which("unzip", true); const args = [file]; - if (!core9.isDebug()) { + if (!core12.isDebug()) { args.unshift("-q"); } args.unshift("-o"); @@ -22302,18 +22310,18 @@ var require_tool_cache = __commonJS({ }); } function cacheDir2(sourceDir, tool, version, arch) { - return __awaiter(this, void 0, void 0, function* () { - version = semver2.clean(version) || version; - arch = arch || os.arch(); - core9.debug(`Caching tool ${tool} ${version} ${arch}`); - core9.debug(`source dir: ${sourceDir}`); + return __awaiter4(this, void 0, void 0, function* () { + version = semver5.clean(version) || version; + arch = arch || os2.arch(); + core12.debug(`Caching tool ${tool} ${version} ${arch}`); + core12.debug(`source dir: ${sourceDir}`); if (!fs.statSync(sourceDir).isDirectory()) { throw new Error("sourceDir is not a directory"); } const destPath = yield _createToolPath(tool, version, arch); for (const itemName of fs.readdirSync(sourceDir)) { const s = path2.join(sourceDir, itemName); - yield io3.cp(s, destPath, { recursive: true }); + yield io4.cp(s, destPath, { recursive: true }); } _completeToolPath(tool, version, arch); return destPath; @@ -22321,18 +22329,18 @@ var require_tool_cache = __commonJS({ } exports2.cacheDir = cacheDir2; function cacheFile(sourceFile, targetFile, tool, version, arch) { - return __awaiter(this, void 0, void 0, function* () { - version = semver2.clean(version) || version; - arch = arch || os.arch(); - core9.debug(`Caching tool ${tool} ${version} ${arch}`); - core9.debug(`source file: ${sourceFile}`); + return __awaiter4(this, void 0, void 0, function* () { + version = semver5.clean(version) || version; + arch = arch || os2.arch(); + core12.debug(`Caching tool ${tool} ${version} ${arch}`); + core12.debug(`source file: ${sourceFile}`); if (!fs.statSync(sourceFile).isFile()) { throw new Error("sourceFile is not a file"); } const destFolder = yield _createToolPath(tool, version, arch); const destPath = path2.join(destFolder, targetFile); - core9.debug(`destination file ${destPath}`); - yield io3.cp(sourceFile, destPath); + core12.debug(`destination file ${destPath}`); + yield io4.cp(sourceFile, destPath); _completeToolPath(tool, version, arch); return destFolder; }); @@ -22345,7 +22353,7 @@ var require_tool_cache = __commonJS({ if (!versionSpec) { throw new Error("versionSpec parameter is required"); } - arch = arch || os.arch(); + arch = arch || os2.arch(); if (!isExplicitVersion(versionSpec)) { const localVersions = findAllVersions(toolName, arch); const match = evaluateVersions(localVersions, versionSpec); @@ -22353,14 +22361,14 @@ var require_tool_cache = __commonJS({ } let toolPath = ""; if (versionSpec) { - versionSpec = semver2.clean(versionSpec) || ""; + versionSpec = semver5.clean(versionSpec) || ""; const cachePath = path2.join(_getCacheDirectory(), toolName, versionSpec, arch); - core9.debug(`checking cache: ${cachePath}`); + core12.debug(`checking cache: ${cachePath}`); if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { - core9.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); + core12.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); toolPath = cachePath; } else { - core9.debug("not found"); + core12.debug("not found"); } } return toolPath; @@ -22368,7 +22376,7 @@ var require_tool_cache = __commonJS({ exports2.find = find2; function findAllVersions(toolName, arch) { const versions = []; - arch = arch || os.arch(); + arch = arch || os2.arch(); const toolPath = path2.join(_getCacheDirectory(), toolName); if (fs.existsSync(toolPath)) { const children = fs.readdirSync(toolPath); @@ -22385,13 +22393,13 @@ var require_tool_cache = __commonJS({ } exports2.findAllVersions = findAllVersions; function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { let releases = []; const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; const http = new httpm.HttpClient("tool-cache"); const headers = {}; if (auth) { - core9.debug("set auth"); + core12.debug("set auth"); headers.authorization = auth; } const response = yield http.getJson(treeUrl, headers); @@ -22412,75 +22420,75 @@ var require_tool_cache = __commonJS({ try { releases = JSON.parse(versionsRaw); } catch (_a) { - core9.debug("Invalid json"); + core12.debug("Invalid json"); } } return releases; }); } exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { - return __awaiter(this, void 0, void 0, function* () { + function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { + return __awaiter4(this, void 0, void 0, function* () { const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); return match; }); } exports2.findFromManifest = findFromManifest; function _createExtractFolder(dest) { - return __awaiter(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (!dest) { dest = path2.join(_getTempDirectory(), crypto.randomUUID()); } - yield io3.mkdirP(dest); + yield io4.mkdirP(dest); return dest; }); } function _createToolPath(tool, version, arch) { - return __awaiter(this, void 0, void 0, function* () { - const folderPath = path2.join(_getCacheDirectory(), tool, semver2.clean(version) || version, arch || ""); - core9.debug(`destination ${folderPath}`); + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path2.join(_getCacheDirectory(), tool, semver5.clean(version) || version, arch || ""); + core12.debug(`destination ${folderPath}`); const markerPath = `${folderPath}.complete`; - yield io3.rmRF(folderPath); - yield io3.rmRF(markerPath); - yield io3.mkdirP(folderPath); + yield io4.rmRF(folderPath); + yield io4.rmRF(markerPath); + yield io4.mkdirP(folderPath); return folderPath; }); } function _completeToolPath(tool, version, arch) { - const folderPath = path2.join(_getCacheDirectory(), tool, semver2.clean(version) || version, arch || ""); + const folderPath = path2.join(_getCacheDirectory(), tool, semver5.clean(version) || version, arch || ""); const markerPath = `${folderPath}.complete`; fs.writeFileSync(markerPath, ""); - core9.debug("finished caching tool"); + core12.debug("finished caching tool"); } function isExplicitVersion(versionSpec) { - const c = semver2.clean(versionSpec) || ""; - core9.debug(`isExplicit: ${c}`); - const valid = semver2.valid(c) != null; - core9.debug(`explicit? ${valid}`); - return valid; + const c = semver5.clean(versionSpec) || ""; + core12.debug(`isExplicit: ${c}`); + const valid2 = semver5.valid(c) != null; + core12.debug(`explicit? ${valid2}`); + return valid2; } exports2.isExplicitVersion = isExplicitVersion; function evaluateVersions(versions, versionSpec) { let version = ""; - core9.debug(`evaluating ${versions.length} versions`); + core12.debug(`evaluating ${versions.length} versions`); versions = versions.sort((a, b) => { - if (semver2.gt(a, b)) { + if (semver5.gt(a, b)) { return 1; } return -1; }); for (let i = versions.length - 1; i >= 0; i--) { const potential = versions[i]; - const satisfied = semver2.satisfies(potential, versionSpec); + const satisfied = semver5.satisfies(potential, versionSpec); if (satisfied) { version = potential; break; } } if (version) { - core9.debug(`matched: ${version}`); + core12.debug(`matched: ${version}`); } else { - core9.debug("match not found"); + core12.debug("match not found"); } return version; } @@ -27780,15 +27788,15 @@ var require_rc2 = __commonJS({ var runPlan = function(plan) { var R = []; for (i = 0; i < 4; i++) { - var val = _input.getInt16Le(); + var val2 = _input.getInt16Le(); if (_iv !== null) { if (encrypt) { - val ^= _iv.getInt16Le(); + val2 ^= _iv.getInt16Le(); } else { - _iv.putInt16Le(val); + _iv.putInt16Le(val2); } } - R.push(val & 65535); + R.push(val2 & 65535); } j = encrypt ? 0 : 63; for (var ptr = 0; ptr < plan.length; ptr++) { @@ -37802,8 +37810,8 @@ var require_ed25519 = __commonJS({ ed25519.privateKeyFromAsn1 = function(obj) { var capture = {}; var errors = []; - var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); - if (!valid) { + var valid2 = forge.asn1.validate(obj, privateKeyValidator, capture, errors); + if (!valid2) { var error2 = new Error("Invalid Key."); error2.errors = errors; throw error2; @@ -37823,8 +37831,8 @@ var require_ed25519 = __commonJS({ ed25519.publicKeyFromAsn1 = function(obj) { var capture = {}; var errors = []; - var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); - if (!valid) { + var valid2 = forge.asn1.validate(obj, publicKeyValidator, capture, errors); + if (!valid2) { var error2 = new Error("Invalid Key."); error2.errors = errors; throw error2; @@ -40196,8 +40204,8 @@ var require_ssh = __commonJS({ } return digest; }; - function _addBigIntegerToBuffer(buffer, val) { - var hexVal = val.toString(16); + function _addBigIntegerToBuffer(buffer, val2) { + var hexVal = val2.toString(16); if (hexVal[0] >= "8") { hexVal = "00" + hexVal; } @@ -40205,9 +40213,9 @@ var require_ssh = __commonJS({ buffer.putInt32(bytes.length); buffer.putBytes(bytes); } - function _addStringToBuffer(buffer, val) { - buffer.putInt32(val.length); - buffer.putString(val); + function _addStringToBuffer(buffer, val2) { + buffer.putInt32(val2.length); + buffer.putString(val2); } function _sha1() { var sha = forge.md.sha1.create(); @@ -40314,7 +40322,7 @@ var require_context = __commonJS({ var require_utils3 = __commonJS({ "node_modules/@actions/github/lib/internal/utils.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -40327,21 +40335,21 @@ var require_utils3 = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { resolve2(value); @@ -40370,7 +40378,7 @@ var require_utils3 = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar(require_lib()); + var httpClient = __importStar4(require_lib()); var undici_1 = require_undici(); function getAuthString(token, options) { if (!token && !options.auth) { @@ -40393,7 +40401,7 @@ var require_utils3 = __commonJS({ exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; function getProxyFetch(destinationUrl) { const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { + const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); return proxyFetch; @@ -40575,7 +40583,7 @@ var require_dist_node2 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -40587,12 +40595,12 @@ var require_dist_node2 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { endpoint: () => endpoint }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); var VERSION = "9.0.6"; var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; @@ -41015,7 +41023,7 @@ var require_dist_node4 = __commonJS({ var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -41035,12 +41043,12 @@ var require_dist_node4 = __commonJS({ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, mod )); - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { RequestError: () => RequestError }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_deprecation = require_dist_node3(); var import_once = __toESM2(require_once()); var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); @@ -41105,7 +41113,7 @@ var require_dist_node5 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -41117,12 +41125,12 @@ var require_dist_node5 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { request: () => request }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; @@ -41315,7 +41323,7 @@ var require_dist_node6 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -41327,12 +41335,12 @@ var require_dist_node6 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { endpoint: () => endpoint }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); var VERSION = "9.0.6"; var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; @@ -41663,7 +41671,7 @@ var require_dist_node7 = __commonJS({ var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -41683,12 +41691,12 @@ var require_dist_node7 = __commonJS({ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, mod )); - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { RequestError: () => RequestError }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_deprecation = require_dist_node3(); var import_once = __toESM2(require_once()); var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); @@ -41753,7 +41761,7 @@ var require_dist_node8 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -41765,12 +41773,12 @@ var require_dist_node8 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { request: () => request }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_endpoint = require_dist_node6(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; @@ -41963,7 +41971,7 @@ var require_dist_node9 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -41975,14 +41983,14 @@ var require_dist_node9 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var index_exports = {}; - __export(index_exports, { + __export2(index_exports, { GraphqlResponseError: () => GraphqlResponseError, graphql: () => graphql2, withCustomRequest: () => withCustomRequest }); - module2.exports = __toCommonJS(index_exports); + module2.exports = __toCommonJS2(index_exports); var import_request3 = require_dist_node8(); var import_universal_user_agent = require_dist_node(); var VERSION = "7.1.1"; @@ -42100,7 +42108,7 @@ var require_dist_node10 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -42112,12 +42120,12 @@ var require_dist_node10 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { createTokenAuth: () => createTokenAuth }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; var REGEX_IS_INSTALLATION = /^ghs_/; var REGEX_IS_USER_TO_SERVER = /^ghu_/; @@ -42171,7 +42179,7 @@ var require_dist_node11 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -42183,12 +42191,12 @@ var require_dist_node11 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { Octokit: () => Octokit }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); var import_before_after_hook = require_before_after_hook(); var import_request = require_dist_node5(); @@ -42330,7 +42338,7 @@ var require_dist_node12 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -42342,13 +42350,13 @@ var require_dist_node12 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { legacyRestEndpointMethods: () => legacyRestEndpointMethods, restEndpointMethods: () => restEndpointMethods }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var VERSION = "10.4.1"; var Endpoints = { actions: { @@ -44486,7 +44494,7 @@ var require_dist_node13 = __commonJS({ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -44498,15 +44506,15 @@ var require_dist_node13 = __commonJS({ } return to; }; - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { composePaginateRest: () => composePaginateRest, isPaginatingEndpoint: () => isPaginatingEndpoint, paginateRest: () => paginateRest, paginatingEndpoints: () => paginatingEndpoints }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var VERSION = "9.2.2"; function normalizePaginatedListResponse(response) { if (!response.data) { @@ -44861,7 +44869,7 @@ var require_dist_node13 = __commonJS({ var require_utils4 = __commonJS({ "node_modules/@actions/github/lib/utils.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -44874,24 +44882,24 @@ var require_utils4 = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getOctokitOptions = exports2.GitHub = exports2.defaults = exports2.context = void 0; - var Context = __importStar(require_context()); - var Utils = __importStar(require_utils3()); + var Context = __importStar4(require_context()); + var Utils = __importStar4(require_utils3()); var core_1 = require_dist_node11(); var plugin_rest_endpoint_methods_1 = require_dist_node12(); var plugin_paginate_rest_1 = require_dist_node13(); @@ -44921,7 +44929,7 @@ var require_utils4 = __commonJS({ var require_github = __commonJS({ "node_modules/@actions/github/lib/github.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -44934,23 +44942,23 @@ var require_github = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); - var __importStar = exports2 && exports2.__importStar || function(mod) { + var __importStar4 = exports2 && exports2.__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); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault(result, mod); + __setModuleDefault4(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getOctokit = exports2.context = void 0; - var Context = __importStar(require_context()); + var Context = __importStar4(require_context()); var utils_1 = require_utils4(); exports2.context = new Context.Context(); function getOctokit(token, options, ...additionalPlugins) { @@ -44966,7 +44974,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -46401,7 +46409,7 @@ var require_dist_node14 = __commonJS({ var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -46421,12 +46429,12 @@ var require_dist_node14 = __commonJS({ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, mod )); - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { RequestError: () => RequestError }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_deprecation = require_dist_node3(); var import_once = __toESM2(require_once()); var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); @@ -46493,7 +46501,7 @@ var require_dist_node15 = __commonJS({ var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export = (target, all) => { + var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; @@ -46513,13 +46521,13 @@ var require_dist_node15 = __commonJS({ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, mod )); - var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; - __export(dist_src_exports, { + __export2(dist_src_exports, { VERSION: () => VERSION, retry: () => retry3 }); - module2.exports = __toCommonJS(dist_src_exports); + module2.exports = __toCommonJS2(dist_src_exports); var import_core = require_dist_node11(); async function errorRequest(state, octokit, error2, options) { if (!error2.request || !error2.request.request) { @@ -46536,11 +46544,11 @@ var require_dist_node15 = __commonJS({ var import_request_error = require_dist_node14(); async function wrapRequest(state, octokit, request, options) { const limiter = new import_light.default(); - limiter.on("failed", function(error2, info3) { + limiter.on("failed", function(error2, info4) { const maxRetries = ~~error2.request.request.retries; const after = ~~error2.request.request.retryAfter; - options.request.retryCount = info3.retryCount + 1; - if (maxRetries > info3.retryCount) { + options.request.retryCount = info4.retryCount + 1; + if (maxRetries > info4.retryCount) { return after * state.retryAfterBaseValue; } }); @@ -46642,378 +46650,45832 @@ var require_console_log_level = __commonJS({ } }); -// src/start-proxy-action.ts -var import_child_process = require("child_process"); -var path = __toESM(require("path")); -var core8 = __toESM(require_core()); -var toolcache = __toESM(require_tool_cache()); -var import_node_forge = __toESM(require_lib2()); - -// src/actions-util.ts -var core4 = __toESM(require_core()); -var toolrunner = __toESM(require_toolrunner()); -var github = __toESM(require_github()); -var io2 = __toESM(require_io()); - -// src/util.ts -var core3 = __toESM(require_core()); -var exec = __toESM(require_exec()); -var io = __toESM(require_io()); +// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-glob-options-helper.js +var require_internal_glob_options_helper = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-glob-options-helper.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getOptions = void 0; + var core12 = __importStar4(require_core()); + function getOptions(copy) { + const result = { + followSymbolicLinks: true, + implicitDescendants: true, + omitBrokenSymbolicLinks: true + }; + if (copy) { + if (typeof copy.followSymbolicLinks === "boolean") { + result.followSymbolicLinks = copy.followSymbolicLinks; + core12.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); + } + if (typeof copy.implicitDescendants === "boolean") { + result.implicitDescendants = copy.implicitDescendants; + core12.debug(`implicitDescendants '${result.implicitDescendants}'`); + } + if (typeof copy.omitBrokenSymbolicLinks === "boolean") { + result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; + core12.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); + } + } + return result; + } + exports2.getOptions = getOptions; + } +}); -// node_modules/get-folder-size/index.js -var import_node_path = require("node:path"); -async function getFolderSize(itemPath, options) { - return await core(itemPath, options, { errors: true }); -} -getFolderSize.loose = async (itemPath, options) => await core(itemPath, options); -getFolderSize.strict = async (itemPath, options) => await core(itemPath, options, { strict: true }); -async function core(rootItemPath, options = {}, returnType = {}) { - const fs = options.fs || await import("node:fs/promises"); - let folderSize = 0n; - const foundInos = /* @__PURE__ */ new Set(); - const errors = []; - await processItem(rootItemPath); - async function processItem(itemPath) { - if (options.ignore?.test(itemPath)) return; - const stats = returnType.strict ? await fs.lstat(itemPath, { bigint: true }) : await fs.lstat(itemPath, { bigint: true }).catch((error2) => errors.push(error2)); - if (typeof stats !== "object") return; - if (!foundInos.has(stats.ino)) { - foundInos.add(stats.ino); - folderSize += stats.size; +// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path-helper.js +var require_internal_path_helper = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path-helper.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.safeTrimTrailingSeparator = exports2.normalizeSeparators = exports2.hasRoot = exports2.hasAbsoluteRoot = exports2.ensureAbsoluteRoot = exports2.dirname = void 0; + var path2 = __importStar4(require("path")); + var assert_1 = __importDefault4(require("assert")); + var IS_WINDOWS = process.platform === "win32"; + function dirname(p) { + p = safeTrimTrailingSeparator(p); + if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { + return p; + } + let result = path2.dirname(p); + if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { + result = safeTrimTrailingSeparator(result); + } + return result; } - if (stats.isDirectory()) { - const directoryItems = returnType.strict ? await fs.readdir(itemPath) : await fs.readdir(itemPath).catch((error2) => errors.push(error2)); - if (typeof directoryItems !== "object") return; - await Promise.all( - directoryItems.map( - (directoryItem) => processItem((0, import_node_path.join)(itemPath, directoryItem)) - ) - ); + exports2.dirname = dirname; + 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`); + if (hasAbsoluteRoot(itemPath)) { + return itemPath; + } + if (IS_WINDOWS) { + 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}'`); + if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { + if (itemPath.length === 2) { + return `${itemPath[0]}:\\${cwd.substr(3)}`; + } else { + if (!cwd.endsWith("\\")) { + cwd += "\\"; + } + return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; + } + } else { + return `${itemPath[0]}:\\${itemPath.substr(2)}`; + } + } 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`); + if (root.endsWith("/") || IS_WINDOWS && root.endsWith("\\")) { + } else { + root += path2.sep; + } + return root + itemPath; } - } - if (!options.bigint) { - if (folderSize > BigInt(Number.MAX_SAFE_INTEGER)) { - const error2 = new RangeError( - "The folder size is too large to return as a Number. You can instruct this package to return a BigInt instead." - ); - if (returnType.strict) { - throw error2; + exports2.ensureAbsoluteRoot = ensureAbsoluteRoot; + function hasAbsoluteRoot(itemPath) { + assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + itemPath = normalizeSeparators(itemPath); + if (IS_WINDOWS) { + return itemPath.startsWith("\\\\") || /^[A-Z]:\\/i.test(itemPath); } - errors.push(error2); - folderSize = Number.MAX_SAFE_INTEGER; - } else { - folderSize = Number(folderSize); + return itemPath.startsWith("/"); } - } - if (returnType.errors) { - return { - size: folderSize, - errors: errors.length > 0 ? errors : null - }; - } else { - return folderSize; - } -} - -// node_modules/js-yaml/dist/js-yaml.mjs -function isNothing(subject) { - return typeof subject === "undefined" || subject === null; -} -function isObject(subject) { - return typeof subject === "object" && subject !== null; -} -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - return [sequence]; -} -function extend(target, source) { - var index, length, key, sourceKeys; - if (source) { - sourceKeys = Object.keys(source); - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; + exports2.hasAbsoluteRoot = hasAbsoluteRoot; + function hasRoot(itemPath) { + assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); + itemPath = normalizeSeparators(itemPath); + if (IS_WINDOWS) { + return itemPath.startsWith("\\") || /^[A-Z]:/i.test(itemPath); + } + return itemPath.startsWith("/"); } - } - return target; -} -function repeat(string, count) { - var result = "", cycle; - for (cycle = 0; cycle < count; cycle += 1) { - result += string; - } - return result; -} -function isNegativeZero(number) { - return number === 0 && Number.NEGATIVE_INFINITY === 1 / number; -} -var isNothing_1 = isNothing; -var isObject_1 = isObject; -var toArray_1 = toArray; -var repeat_1 = repeat; -var isNegativeZero_1 = isNegativeZero; -var extend_1 = extend; -var common = { - isNothing: isNothing_1, - isObject: isObject_1, - toArray: toArray_1, - repeat: repeat_1, - isNegativeZero: isNegativeZero_1, - extend: extend_1 -}; -function formatError(exception2, compact) { - var where = "", message = exception2.reason || "(unknown reason)"; - if (!exception2.mark) return message; - if (exception2.mark.name) { - where += 'in "' + exception2.mark.name + '" '; - } - where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")"; - if (!compact && exception2.mark.snippet) { - where += "\n\n" + exception2.mark.snippet; - } - return message + " " + where; -} -function YAMLException$1(reason, mark) { - Error.call(this); - this.name = "YAMLException"; - this.reason = reason; - this.mark = mark; - this.message = formatError(this, false); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = new Error().stack || ""; - } -} -YAMLException$1.prototype = Object.create(Error.prototype); -YAMLException$1.prototype.constructor = YAMLException$1; -YAMLException$1.prototype.toString = function toString(compact) { - return this.name + ": " + formatError(this, compact); -}; -var exception = YAMLException$1; -function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ""; - var tail = ""; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; - if (position - lineStart > maxHalfLength) { - head = " ... "; - lineStart = position - maxHalfLength + head.length; - } - if (lineEnd - position > maxHalfLength) { - tail = " ..."; - lineEnd = position + maxHalfLength - tail.length; - } - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail, - pos: position - lineStart + head.length - // relative position - }; -} -function padStart(string, max) { - return common.repeat(" ", max - string.length) + string; -} -function makeSnippet(mark, options) { - options = Object.create(options || null); - if (!mark.buffer) return null; - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== "number") options.indent = 1; - if (typeof options.linesBefore !== "number") options.linesBefore = 3; - if (typeof options.linesAfter !== "number") options.linesAfter = 2; - var re = /\r?\n|\r|\0/g; - var lineStarts = [0]; - var lineEnds = []; - var match; - var foundLineNo = -1; - while (match = re.exec(mark.buffer)) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; + exports2.hasRoot = hasRoot; + function normalizeSeparators(p) { + p = p || ""; + if (IS_WINDOWS) { + p = p.replace(/\//g, "\\"); + const isUnc = /^\\\\+[^\\]/.test(p); + return (isUnc ? "\\" : "") + p.replace(/\\\\+/g, "\\"); + } + return p.replace(/\/\/+/g, "/"); } + exports2.normalizeSeparators = normalizeSeparators; + function safeTrimTrailingSeparator(p) { + if (!p) { + return ""; + } + p = normalizeSeparators(p); + if (!p.endsWith(path2.sep)) { + return p; + } + if (p === path2.sep) { + return p; + } + if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { + return p; + } + return p.substr(0, p.length - 1); + } + exports2.safeTrimTrailingSeparator = safeTrimTrailingSeparator; } - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; - var result = "", i, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); - for (i = 1; i <= options.linesBefore; i++) { - if (foundLineNo - i < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i], - lineEnds[foundLineNo - i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), - maxLineLength - ); - result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; - } - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; - result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; - for (i = 1; i <= options.linesAfter; i++) { - if (foundLineNo + i >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i], - lineEnds[foundLineNo + i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), - maxLineLength - ); - result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\n"; +}); + +// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-match-kind.js +var require_internal_match_kind = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-match-kind.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MatchKind = void 0; + var MatchKind; + (function(MatchKind2) { + MatchKind2[MatchKind2["None"] = 0] = "None"; + MatchKind2[MatchKind2["Directory"] = 1] = "Directory"; + MatchKind2[MatchKind2["File"] = 2] = "File"; + MatchKind2[MatchKind2["All"] = 3] = "All"; + })(MatchKind = exports2.MatchKind || (exports2.MatchKind = {})); } - return result.replace(/\n$/, ""); -} -var snippet = makeSnippet; -var TYPE_CONSTRUCTOR_OPTIONS = [ - "kind", - "multi", - "resolve", - "construct", - "instanceOf", - "predicate", - "represent", - "representName", - "defaultStyle", - "styleAliases" -]; -var YAML_NODE_KINDS = [ - "scalar", - "sequence", - "mapping" -]; -function compileStyleAliases(map2) { - var result = {}; - if (map2 !== null) { - Object.keys(map2).forEach(function(style) { - map2[style].forEach(function(alias) { - result[String(alias)] = style; - }); +}); + +// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern-helper.js +var require_internal_pattern_helper = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern-helper.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; }); - } - return result; -} -function Type$1(tag, options) { - options = options || {}; - Object.keys(options).forEach(function(name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.partialMatch = exports2.match = exports2.getSearchPaths = void 0; + var pathHelper = __importStar4(require_internal_path_helper()); + var internal_match_kind_1 = require_internal_match_kind(); + var IS_WINDOWS = process.platform === "win32"; + function getSearchPaths(patterns) { + patterns = patterns.filter((x) => !x.negate); + 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) { + const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; + if (searchPathMap[key] === "included") { + continue; + } + 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); + } + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = "included"; + } + } + return result; } - }); - this.options = options; - this.tag = tag; - this.kind = options["kind"] || null; - this.resolve = options["resolve"] || function() { - return true; - }; - this.construct = options["construct"] || function(data) { - return data; - }; - this.instanceOf = options["instanceOf"] || null; - this.predicate = options["predicate"] || null; - this.represent = options["represent"] || null; - this.representName = options["representName"] || null; - this.defaultStyle = options["defaultStyle"] || null; - this.multi = options["multi"] || false; - this.styleAliases = compileStyleAliases(options["styleAliases"] || null); - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} -var type = Type$1; -function compileList(schema2, name) { - var result = []; - schema2[name].forEach(function(currentType) { - var newIndex = result.length; - result.forEach(function(previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { - newIndex = previousIndex; + exports2.getSearchPaths = getSearchPaths; + 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); + } } - }); - result[newIndex] = currentType; - }); - return result; -} -function compileMap() { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] + return result; } - }, index, length; - function collectType(type2) { - if (type2.multi) { - result.multi[type2.kind].push(type2); - result.multi["fallback"].push(type2); - } else { - result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2; + exports2.match = match; + function partialMatch(patterns, itemPath) { + return patterns.some((x) => !x.negate && x.partialMatch(itemPath)); } + exports2.partialMatch = partialMatch; } - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); +}); + +// node_modules/concat-map/index.js +var require_concat_map = __commonJS({ + "node_modules/concat-map/index.js"(exports2, module2) { + module2.exports = function(xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; + }; + var isArray = Array.isArray || function(xs) { + return Object.prototype.toString.call(xs) === "[object Array]"; + }; } - return result; -} -function Schema$1(definition) { - return this.extend(definition); -} -Schema$1.prototype.extend = function extend2(definition) { - var implicit = []; - var explicit = []; - if (definition instanceof type) { - explicit.push(definition); - } else if (Array.isArray(definition)) { - explicit = explicit.concat(definition); - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); - } else { - throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); +}); + +// node_modules/balanced-match/index.js +var require_balanced_match = __commonJS({ + "node_modules/balanced-match/index.js"(exports2, module2) { + "use strict"; + module2.exports = balanced; + function balanced(a, b, str2) { + if (a instanceof RegExp) a = maybeMatch(a, str2); + if (b instanceof RegExp) b = maybeMatch(b, str2); + var r = range(a, b, str2); + return r && { + start: r[0], + end: r[1], + pre: str2.slice(0, r[0]), + body: str2.slice(r[0] + a.length, r[1]), + post: str2.slice(r[1] + b.length) + }; + } + function maybeMatch(reg, str2) { + var m = str2.match(reg); + return m ? m[0] : null; + } + balanced.range = range; + function range(a, b, str2) { + var begs, beg, left, right, result; + var ai = str2.indexOf(a); + var bi = str2.indexOf(b, ai + 1); + var i = ai; + if (ai >= 0 && bi > 0) { + begs = []; + left = str2.length; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str2.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [begs.pop(), bi]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + bi = str2.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length) { + result = [left, right]; + } + } + return result; + } } - implicit.forEach(function(type$1) { - if (!(type$1 instanceof type)) { - throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); +}); + +// node_modules/brace-expansion/index.js +var require_brace_expansion = __commonJS({ + "node_modules/brace-expansion/index.js"(exports2, module2) { + var concatMap = require_concat_map(); + var balanced = require_balanced_match(); + module2.exports = expandTop; + var escSlash = "\0SLASH" + Math.random() + "\0"; + var escOpen = "\0OPEN" + Math.random() + "\0"; + var escClose = "\0CLOSE" + Math.random() + "\0"; + var escComma = "\0COMMA" + Math.random() + "\0"; + var escPeriod = "\0PERIOD" + Math.random() + "\0"; + function numeric(str2) { + return parseInt(str2, 10) == str2 ? parseInt(str2, 10) : str2.charCodeAt(0); + } + function escapeBraces(str2) { + return str2.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod); + } + function unescapeBraces(str2) { + return str2.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join("."); + } + function parseCommaParts(str2) { + if (!str2) + return [""]; + var parts = []; + var m = balanced("{", "}", str2); + if (!m) + return str2.split(","); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(","); + p[p.length - 1] += "{" + body + "}"; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; + } + function expandTop(str2) { + if (!str2) + return []; + if (str2.substr(0, 2) === "{}") { + str2 = "\\{\\}" + str2.substr(2); + } + return expand(escapeBraces(str2), true).map(unescapeBraces); } - if (type$1.loadKind && type$1.loadKind !== "scalar") { - throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); + function embrace(str2) { + return "{" + str2 + "}"; } - if (type$1.multi) { - throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); + function isPadded(el) { + return /^-?0\d/.test(el); } - }); - explicit.forEach(function(type$1) { - if (!(type$1 instanceof type)) { - throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); + function lte(i, y) { + return i <= y; + } + function gte3(i, y) { + return i >= y; + } + function expand(str2, isTop) { + var expansions = []; + var m = balanced("{", "}", str2); + if (!m || /\$$/.test(m.pre)) return [str2]; + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(",") >= 0; + if (!isSequence && !isOptions) { + if (m.post.match(/,(?!,).*\}/)) { + str2 = m.pre + "{" + m.body + escClose + m.post; + return expand(str2); + } + return [str2]; + } + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length ? expand(m.post, false) : [""]; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + var pre = m.pre; + var post = m.post.length ? expand(m.post, false) : [""]; + var N; + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte3; + } + var pad = n.some(isPadded); + N = []; + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === "\\") + c = ""; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join("0"); + if (i < 0) + c = "-" + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { + return expand(el, false); + }); + } + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + return expansions; } - }); - var result = Object.create(Schema$1.prototype); - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); - result.compiledImplicit = compileList(result, "implicit"); - result.compiledExplicit = compileList(result, "explicit"); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); - return result; -}; -var schema = Schema$1; -var str = new type("tag:yaml.org,2002:str", { - kind: "scalar", - construct: function(data) { - return data !== null ? data : ""; - } -}); -var seq = new type("tag:yaml.org,2002:seq", { - kind: "sequence", - construct: function(data) { - return data !== null ? data : []; } }); -var map = new type("tag:yaml.org,2002:map", { - kind: "mapping", + +// node_modules/minimatch/minimatch.js +var require_minimatch = __commonJS({ + "node_modules/minimatch/minimatch.js"(exports2, module2) { + module2.exports = minimatch; + minimatch.Minimatch = Minimatch; + var path2 = (function() { + try { + return require("path"); + } catch (e) { + } + })() || { + sep: "/" + }; + minimatch.sep = path2.sep; + var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; + var expand = require_brace_expansion(); + var plTypes = { + "!": { open: "(?:(?!(?:", close: "))[^/]*?)" }, + "?": { open: "(?:", close: ")?" }, + "+": { open: "(?:", close: ")+" }, + "*": { open: "(?:", close: ")*" }, + "@": { open: "(?:", close: ")" } + }; + var qmark = "[^/]"; + var star = qmark + "*?"; + var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?"; + var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; + var reSpecials = charSet("().*{}+?[]^$\\!"); + function charSet(s) { + return s.split("").reduce(function(set2, c) { + set2[c] = true; + return set2; + }, {}); + } + var slashSplit = /\/+/; + minimatch.filter = filter; + function filter(pattern, options) { + options = options || {}; + return function(p, i, list) { + return minimatch(p, pattern, options); + }; + } + function ext(a, b) { + b = b || {}; + var t = {}; + Object.keys(a).forEach(function(k) { + t[k] = a[k]; + }); + Object.keys(b).forEach(function(k) { + t[k] = b[k]; + }); + return t; + } + minimatch.defaults = function(def) { + if (!def || typeof def !== "object" || !Object.keys(def).length) { + return minimatch; + } + var orig = minimatch; + var m = function minimatch2(p, pattern, options) { + return orig(p, pattern, ext(def, options)); + }; + m.Minimatch = function Minimatch2(pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)); + }; + m.Minimatch.defaults = function defaults(options) { + return orig.defaults(ext(def, options)).Minimatch; + }; + m.filter = function filter2(pattern, options) { + return orig.filter(pattern, ext(def, options)); + }; + m.defaults = function defaults(options) { + return orig.defaults(ext(def, options)); + }; + m.makeRe = function makeRe2(pattern, options) { + return orig.makeRe(pattern, ext(def, options)); + }; + m.braceExpand = function braceExpand2(pattern, options) { + return orig.braceExpand(pattern, ext(def, options)); + }; + m.match = function(list, pattern, options) { + return orig.match(list, pattern, ext(def, options)); + }; + return m; + }; + Minimatch.defaults = function(def) { + return minimatch.defaults(def).Minimatch; + }; + function minimatch(p, pattern, options) { + assertValidPattern(pattern); + if (!options) options = {}; + if (!options.nocomment && pattern.charAt(0) === "#") { + return false; + } + return new Minimatch(pattern, options).match(p); + } + function Minimatch(pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options); + } + assertValidPattern(pattern); + if (!options) options = {}; + pattern = pattern.trim(); + if (!options.allowWindowsEscape && path2.sep !== "/") { + pattern = pattern.split(path2.sep).join("/"); + } + this.options = options; + this.set = []; + this.pattern = pattern; + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.make(); + } + Minimatch.prototype.debug = function() { + }; + Minimatch.prototype.make = make; + function make() { + var pattern = this.pattern; + var options = this.options; + if (!options.nocomment && pattern.charAt(0) === "#") { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + this.parseNegate(); + var set2 = this.globSet = this.braceExpand(); + if (options.debug) this.debug = function debug3() { + console.error.apply(console, arguments); + }; + this.debug(this.pattern, set2); + set2 = this.globParts = set2.map(function(s) { + return s.split(slashSplit); + }); + this.debug(this.pattern, set2); + set2 = set2.map(function(s, si, set3) { + return s.map(this.parse, this); + }, this); + this.debug(this.pattern, set2); + set2 = set2.filter(function(s) { + return s.indexOf(false) === -1; + }); + this.debug(this.pattern, set2); + this.set = set2; + } + Minimatch.prototype.parseNegate = parseNegate; + function parseNegate() { + var pattern = this.pattern; + var negate = false; + var options = this.options; + var negateOffset = 0; + if (options.nonegate) return; + for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) { + negate = !negate; + negateOffset++; + } + if (negateOffset) this.pattern = pattern.substr(negateOffset); + this.negate = negate; + } + minimatch.braceExpand = function(pattern, options) { + return braceExpand(pattern, options); + }; + Minimatch.prototype.braceExpand = braceExpand; + function braceExpand(pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options; + } else { + options = {}; + } + } + pattern = typeof pattern === "undefined" ? this.pattern : pattern; + assertValidPattern(pattern); + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + return [pattern]; + } + return expand(pattern); + } + var MAX_PATTERN_LENGTH = 1024 * 64; + var assertValidPattern = function(pattern) { + if (typeof pattern !== "string") { + throw new TypeError("invalid pattern"); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError("pattern is too long"); + } + }; + Minimatch.prototype.parse = parse; + var SUBPARSE = {}; + function parse(pattern, isSub) { + assertValidPattern(pattern); + var options = this.options; + if (pattern === "**") { + if (!options.noglobstar) + return GLOBSTAR; + else + pattern = "*"; + } + if (pattern === "") return ""; + var re = ""; + var hasMagic = !!options.nocase; + var escaping = false; + var patternListStack = []; + var negativeLists = []; + var stateChar; + var inClass = false; + var reClassStart = -1; + var classStart = -1; + var patternStart = pattern.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)"; + var self2 = this; + function clearStateChar() { + if (stateChar) { + switch (stateChar) { + case "*": + re += star; + hasMagic = true; + break; + case "?": + re += qmark; + hasMagic = true; + break; + default: + re += "\\" + stateChar; + break; + } + self2.debug("clearStateChar %j %j", stateChar, re); + stateChar = false; + } + } + for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) { + this.debug("%s %s %s %j", pattern, i, re, c); + if (escaping && reSpecials[c]) { + re += "\\" + c; + escaping = false; + continue; + } + switch (c) { + /* istanbul ignore next */ + case "/": { + return false; + } + case "\\": + clearStateChar(); + escaping = true; + continue; + // the various stateChar values + // for the "extglob" stuff. + case "?": + case "*": + case "+": + case "@": + case "!": + this.debug("%s %s %s %j <-- stateChar", pattern, i, re, c); + if (inClass) { + this.debug(" in class"); + if (c === "!" && i === classStart + 1) c = "^"; + re += c; + continue; + } + self2.debug("call clearStateChar %j", stateChar); + clearStateChar(); + stateChar = c; + if (options.noext) clearStateChar(); + continue; + case "(": + if (inClass) { + re += "("; + continue; + } + if (!stateChar) { + re += "\\("; + continue; + } + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }); + re += stateChar === "!" ? "(?:(?!(?:" : "(?:"; + this.debug("plType %j %j", stateChar, re); + stateChar = false; + continue; + case ")": + if (inClass || !patternListStack.length) { + re += "\\)"; + continue; + } + clearStateChar(); + hasMagic = true; + var pl = patternListStack.pop(); + re += pl.close; + if (pl.type === "!") { + negativeLists.push(pl); + } + pl.reEnd = re.length; + continue; + case "|": + if (inClass || !patternListStack.length || escaping) { + re += "\\|"; + escaping = false; + continue; + } + clearStateChar(); + re += "|"; + continue; + // these are mostly the same in regexp and glob + case "[": + clearStateChar(); + if (inClass) { + re += "\\" + c; + continue; + } + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue; + case "]": + if (i === classStart + 1 || !inClass) { + re += "\\" + c; + escaping = false; + continue; + } + var cs = pattern.substring(classStart + 1, i); + try { + RegExp("[" + cs + "]"); + } catch (er) { + var sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + "\\[" + sp[0] + "\\]"; + hasMagic = hasMagic || sp[1]; + inClass = false; + continue; + } + hasMagic = true; + inClass = false; + re += c; + continue; + default: + clearStateChar(); + if (escaping) { + escaping = false; + } else if (reSpecials[c] && !(c === "^" && inClass)) { + re += "\\"; + } + re += c; + } + } + if (inClass) { + cs = pattern.substr(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + "\\[" + sp[0]; + hasMagic = hasMagic || sp[1]; + } + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length); + this.debug("setting tail", re, pl); + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function(_, $1, $2) { + if (!$2) { + $2 = "\\"; + } + return $1 + $1 + $2 + "|"; + }); + this.debug("tail=%j\n %s", tail, tail, pl, re); + var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; + hasMagic = true; + re = re.slice(0, pl.reStart) + t + "\\(" + tail; + } + clearStateChar(); + if (escaping) { + re += "\\\\"; + } + var addPatternStart = false; + switch (re.charAt(0)) { + case "[": + case ".": + case "(": + addPatternStart = true; + } + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n]; + var nlBefore = re.slice(0, nl.reStart); + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); + var nlAfter = re.slice(nl.reEnd); + nlLast += nlAfter; + var openParensBefore = nlBefore.split("(").length - 1; + var cleanAfter = nlAfter; + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ""); + } + nlAfter = cleanAfter; + var dollar = ""; + if (nlAfter === "" && isSub !== SUBPARSE) { + dollar = "$"; + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; + re = newRe; + } + if (re !== "" && hasMagic) { + re = "(?=.)" + re; + } + if (addPatternStart) { + re = patternStart + re; + } + if (isSub === SUBPARSE) { + return [re, hasMagic]; + } + if (!hasMagic) { + return globUnescape(pattern); + } + var flags = options.nocase ? "i" : ""; + try { + var regExp = new RegExp("^" + re + "$", flags); + } catch (er) { + return new RegExp("$."); + } + regExp._glob = pattern; + regExp._src = re; + return regExp; + } + minimatch.makeRe = function(pattern, options) { + return new Minimatch(pattern, options || {}).makeRe(); + }; + Minimatch.prototype.makeRe = makeRe; + function makeRe() { + if (this.regexp || this.regexp === false) return this.regexp; + var set2 = this.set; + if (!set2.length) { + this.regexp = false; + return this.regexp; + } + var options = this.options; + var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot; + var flags = options.nocase ? "i" : ""; + var re = set2.map(function(pattern) { + return pattern.map(function(p) { + return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src; + }).join("\\/"); + }).join("|"); + re = "^(?:" + re + ")$"; + if (this.negate) re = "^(?!" + re + ").*$"; + try { + this.regexp = new RegExp(re, flags); + } catch (ex) { + this.regexp = false; + } + return this.regexp; + } + minimatch.match = function(list, pattern, options) { + options = options || {}; + var mm = new Minimatch(pattern, options); + list = list.filter(function(f) { + return mm.match(f); + }); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; + }; + Minimatch.prototype.match = function match(f, partial) { + if (typeof partial === "undefined") partial = this.partial; + this.debug("match", f, this.pattern); + if (this.comment) return false; + if (this.empty) return f === ""; + if (f === "/" && partial) return true; + var options = this.options; + if (path2.sep !== "/") { + f = f.split(path2.sep).join("/"); + } + f = f.split(slashSplit); + this.debug(this.pattern, "split", f); + var set2 = this.set; + this.debug(this.pattern, "set", set2); + var filename; + var i; + for (i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break; + } + for (i = 0; i < set2.length; i++) { + var pattern = set2[i]; + var file = f; + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + var hit = this.matchOne(file, pattern, partial); + if (hit) { + if (options.flipNegate) return true; + return !this.negate; + } + } + if (options.flipNegate) return false; + return this.negate; + }; + Minimatch.prototype.matchOne = function(file, pattern, partial) { + var options = this.options; + this.debug( + "matchOne", + { "this": this, file, pattern } + ); + this.debug("matchOne", file.length, pattern.length); + for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { + this.debug("matchOne loop"); + var p = pattern[pi]; + var f = file[fi]; + this.debug(pattern, p, f); + if (p === false) return false; + if (p === GLOBSTAR) { + this.debug("GLOBSTAR", [pattern, p, f]); + var fr = fi; + var pr = pi + 1; + if (pr === pl) { + this.debug("** at the end"); + for (; fi < fl; fi++) { + if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false; + } + return true; + } + while (fr < fl) { + var swallowee = file[fr]; + this.debug("\nglobstar while", file, fr, pattern, pr, swallowee); + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug("globstar found match!", fr, fl, swallowee); + return true; + } else { + if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") { + this.debug("dot detected!", file, fr, pattern, pr); + break; + } + this.debug("globstar swallow a segment, and continue"); + fr++; + } + } + if (partial) { + this.debug("\n>>> no match, partial?", file, fr, pattern, pr); + if (fr === fl) return true; + } + return false; + } + var hit; + if (typeof p === "string") { + hit = f === p; + this.debug("string match", p, f, hit); + } else { + hit = f.match(p); + this.debug("pattern match", p, f, hit); + } + if (!hit) return false; + } + if (fi === fl && pi === pl) { + return true; + } else if (fi === fl) { + return partial; + } else if (pi === pl) { + return fi === fl - 1 && file[fi] === ""; + } + throw new Error("wtf?"); + }; + function globUnescape(s) { + return s.replace(/\\(.)/g, "$1"); + } + function regExpEscape(s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + } + } +}); + +// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path.js +var require_internal_path = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Path = void 0; + var path2 = __importStar4(require("path")); + var pathHelper = __importStar4(require_internal_path_helper()); + var assert_1 = __importDefault4(require("assert")); + var IS_WINDOWS = process.platform === "win32"; + var Path = class { + /** + * Constructs a Path + * @param itemPath Path or array of segments + */ + constructor(itemPath) { + this.segments = []; + if (typeof itemPath === "string") { + assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path2.sep); + } else { + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + const basename = path2.basename(remaining); + this.segments.unshift(basename); + remaining = dir; + dir = pathHelper.dirname(remaining); + } + this.segments.unshift(remaining); + } + } else { + assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + for (let i = 0; i < itemPath.length; i++) { + let segment = itemPath[i]; + assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); + segment = pathHelper.normalizeSeparators(itemPath[i]); + 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); + } else { + assert_1.default(!segment.includes(path2.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } + } + } + /** + * Converts the path to it's string representation + */ + toString() { + let result = this.segments[0]; + let skipSlash = result.endsWith(path2.sep) || IS_WINDOWS && /^[A-Z]:$/i.test(result); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } else { + result += path2.sep; + } + result += this.segments[i]; + } + return result; + } + }; + exports2.Path = Path; + } +}); + +// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern.js +var require_internal_pattern = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Pattern = void 0; + var os2 = __importStar4(require("os")); + var path2 = __importStar4(require("path")); + var pathHelper = __importStar4(require_internal_path_helper()); + var assert_1 = __importDefault4(require("assert")); + var minimatch_1 = require_minimatch(); + var internal_match_kind_1 = require_internal_match_kind(); + var internal_path_1 = require_internal_path(); + var IS_WINDOWS = process.platform === "win32"; + var Pattern = class _Pattern { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { + this.negate = false; + let pattern; + if (typeof patternOrNegate === "string") { + pattern = patternOrNegate.trim(); + } else { + 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}`; + } + } + while (pattern.startsWith("!")) { + this.negate = !this.negate; + pattern = pattern.substr(1).trim(); + } + pattern = _Pattern.fixupPattern(pattern, homedir); + this.segments = new internal_path_1.Path(pattern).segments; + this.trailingSeparator = pathHelper.normalizeSeparators(pattern).endsWith(path2.sep); + pattern = pathHelper.safeTrimTrailingSeparator(pattern); + 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(); + this.rootRegExp = new RegExp(_Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? "i" : ""); + this.isImplicitPattern = isImplicitPattern; + 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) { + if (this.segments[this.segments.length - 1] === "**") { + itemPath = pathHelper.normalizeSeparators(itemPath); + if (!itemPath.endsWith(path2.sep) && this.isImplicitPattern === false) { + itemPath = `${itemPath}${path2.sep}`; + } + } else { + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + } + 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) { + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + 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, "\\\\")).replace(/(\[)(?=[^/]+\])/g, "[[]").replace(/\?/g, "[?]").replace(/\*/g, "[*]"); + } + /** + * Normalizes slashes and ensures absolute root + */ + static fixupPattern(pattern, homedir) { + assert_1.default(pattern, "pattern cannot be empty"); + 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.`); + assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + pattern = pathHelper.normalizeSeparators(pattern); + if (pattern === "." || pattern.startsWith(`.${path2.sep}`)) { + pattern = _Pattern.globEscape(process.cwd()) + pattern.substr(1); + } else if (pattern === "~" || pattern.startsWith(`~${path2.sep}`)) { + homedir = homedir || os2.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); + } 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); + } 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); + } 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]; + if (c === "\\" && !IS_WINDOWS && i + 1 < segment.length) { + literal += segment[++i]; + continue; + } else if (c === "*" || c === "?") { + return ""; + } else if (c === "[" && i + 1 < segment.length) { + let set2 = ""; + let closed = -1; + for (let i2 = i + 1; i2 < segment.length; i2++) { + const c2 = segment[i2]; + if (c2 === "\\" && !IS_WINDOWS && i2 + 1 < segment.length) { + set2 += segment[++i2]; + continue; + } else if (c2 === "]") { + closed = i2; + break; + } else { + set2 += c2; + } + } + if (closed >= 0) { + if (set2.length > 1) { + return ""; + } + if (set2) { + literal += set2; + i = closed; + continue; + } + } + } + literal += c; + } + return literal; + } + /** + * Escapes regexp special characters + * https://javascript.info/regexp-escaping + */ + static regExpEscape(s) { + return s.replace(/[[\\^$.|?*+()]/g, "\\$&"); + } + }; + exports2.Pattern = Pattern; + } +}); + +// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-search-state.js +var require_internal_search_state = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-search-state.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SearchState = void 0; + var SearchState = class { + constructor(path2, level) { + this.path = path2; + this.level = level; + } + }; + exports2.SearchState = SearchState; + } +}); + +// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-globber.js +var require_internal_globber = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-globber.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __asyncValues4 = exports2 && exports2.__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(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } + }; + var __await4 = exports2 && exports2.__await || function(v) { + return this instanceof __await4 ? (this.v = v, this) : new __await4(v); + }; + var __asyncGenerator4 = exports2 && exports2.__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 __await4 ? 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(exports2, "__esModule", { value: true }); + exports2.DefaultGlobber = void 0; + var core12 = __importStar4(require_core()); + var fs = __importStar4(require("fs")); + var globOptionsHelper = __importStar4(require_internal_glob_options_helper()); + var path2 = __importStar4(require("path")); + var patternHelper = __importStar4(require_internal_pattern_helper()); + var internal_match_kind_1 = require_internal_match_kind(); + var internal_pattern_1 = require_internal_pattern(); + var internal_search_state_1 = require_internal_search_state(); + var IS_WINDOWS = process.platform === "win32"; + var DefaultGlobber = class _DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); + } + getSearchPaths() { + return this.searchPaths.slice(); + } + glob() { + var e_1, _a; + return __awaiter4(this, void 0, void 0, function* () { + const result = []; + try { + for (var _b = __asyncValues4(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 __asyncGenerator4(this, arguments, function* globGenerator_1() { + const options = globOptionsHelper.getOptions(this.options); + 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("**"))); + } + } + const stack = []; + for (const searchPath of patternHelper.getSearchPaths(patterns)) { + core12.debug(`Search path '${searchPath}'`); + try { + yield __await4(fs.promises.lstat(searchPath)); + } catch (err) { + if (err.code === "ENOENT") { + continue; + } + throw err; + } + stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); + } + const traversalChain = []; + while (stack.length) { + const item = stack.pop(); + const match = patternHelper.match(patterns, item.path); + const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); + if (!match && !partialMatch) { + continue; + } + const stats = yield __await4( + _DefaultGlobber.stat(item, options, traversalChain) + // Broken symlink, or symlink cycle detected, or no longer exists + ); + if (!stats) { + continue; + } + if (stats.isDirectory()) { + if (match & internal_match_kind_1.MatchKind.Directory) { + yield yield __await4(item.path); + } else if (!partialMatch) { + continue; + } + const childLevel = item.level + 1; + const childItems = (yield __await4(fs.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path2.join(item.path, x), childLevel)); + stack.push(...childItems.reverse()); + } else if (match & internal_match_kind_1.MatchKind.File) { + yield yield __await4(item.path); + } + } + }); + } + /** + * Constructs a DefaultGlobber + */ + static create(patterns, options) { + return __awaiter4(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) { + if (!line || line.startsWith("#")) { + continue; + } 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 __awaiter4(this, void 0, void 0, function* () { + let stats; + if (options.followSymbolicLinks) { + try { + stats = yield fs.promises.stat(item.path); + } catch (err) { + if (err.code === "ENOENT") { + if (options.omitBrokenSymbolicLinks) { + core12.debug(`Broken symlink '${item.path}'`); + return void 0; + } + throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + } + throw err; + } + } else { + stats = yield fs.promises.lstat(item.path); + } + if (stats.isDirectory() && options.followSymbolicLinks) { + const realPath = yield fs.promises.realpath(item.path); + while (traversalChain.length >= item.level) { + traversalChain.pop(); + } + if (traversalChain.some((x) => x === realPath)) { + core12.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + return void 0; + } + traversalChain.push(realPath); + } + return stats; + }); + } + }; + exports2.DefaultGlobber = DefaultGlobber; + } +}); + +// node_modules/@actions/cache/node_modules/@actions/glob/lib/glob.js +var require_glob = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/glob/lib/glob.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.create = void 0; + var internal_globber_1 = require_internal_globber(); + function create(patterns, options) { + return __awaiter4(this, void 0, void 0, function* () { + return yield internal_globber_1.DefaultGlobber.create(patterns, options); + }); + } + exports2.create = create; + } +}); + +// node_modules/@actions/cache/node_modules/semver/semver.js +var require_semver3 = __commonJS({ + "node_modules/@actions/cache/node_modules/semver/semver.js"(exports2, module2) { + exports2 = module2.exports = SemVer; + var debug3; + if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug3 = function() { + var args = Array.prototype.slice.call(arguments, 0); + args.unshift("SEMVER"); + console.log.apply(console, args); + }; + } else { + debug3 = function() { + }; + } + exports2.SEMVER_SPEC_VERSION = "2.0.0"; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ + 9007199254740991; + var MAX_SAFE_COMPONENT_LENGTH = 16; + var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; + var re = exports2.re = []; + var safeRe = exports2.safeRe = []; + var src = exports2.src = []; + var t = exports2.tokens = {}; + var R = 0; + function tok(n) { + t[n] = R++; + } + var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; + var safeRegexReplacements = [ + ["\\s", 1], + ["\\d", MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] + ]; + function makeSafeRe(value) { + for (var i2 = 0; i2 < safeRegexReplacements.length; i2++) { + var token = safeRegexReplacements[i2][0]; + var max = safeRegexReplacements[i2][1]; + value = value.split(token + "*").join(token + "{0," + max + "}").split(token + "+").join(token + "{1," + max + "}"); + } + return value; + } + tok("NUMERICIDENTIFIER"); + src[t.NUMERICIDENTIFIER] = "0|[1-9]\\d*"; + tok("NUMERICIDENTIFIERLOOSE"); + src[t.NUMERICIDENTIFIERLOOSE] = "\\d+"; + tok("NONNUMERICIDENTIFIER"); + src[t.NONNUMERICIDENTIFIER] = "\\d*[a-zA-Z-]" + LETTERDASHNUMBER + "*"; + tok("MAINVERSION"); + src[t.MAINVERSION] = "(" + src[t.NUMERICIDENTIFIER] + ")\\.(" + src[t.NUMERICIDENTIFIER] + ")\\.(" + src[t.NUMERICIDENTIFIER] + ")"; + tok("MAINVERSIONLOOSE"); + src[t.MAINVERSIONLOOSE] = "(" + src[t.NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[t.NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[t.NUMERICIDENTIFIERLOOSE] + ")"; + tok("PRERELEASEIDENTIFIER"); + src[t.PRERELEASEIDENTIFIER] = "(?:" + src[t.NUMERICIDENTIFIER] + "|" + src[t.NONNUMERICIDENTIFIER] + ")"; + tok("PRERELEASEIDENTIFIERLOOSE"); + src[t.PRERELEASEIDENTIFIERLOOSE] = "(?:" + src[t.NUMERICIDENTIFIERLOOSE] + "|" + src[t.NONNUMERICIDENTIFIER] + ")"; + tok("PRERELEASE"); + src[t.PRERELEASE] = "(?:-(" + src[t.PRERELEASEIDENTIFIER] + "(?:\\." + src[t.PRERELEASEIDENTIFIER] + ")*))"; + tok("PRERELEASELOOSE"); + src[t.PRERELEASELOOSE] = "(?:-?(" + src[t.PRERELEASEIDENTIFIERLOOSE] + "(?:\\." + src[t.PRERELEASEIDENTIFIERLOOSE] + ")*))"; + tok("BUILDIDENTIFIER"); + src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + "+"; + tok("BUILD"); + src[t.BUILD] = "(?:\\+(" + src[t.BUILDIDENTIFIER] + "(?:\\." + src[t.BUILDIDENTIFIER] + ")*))"; + tok("FULL"); + tok("FULLPLAIN"); + src[t.FULLPLAIN] = "v?" + src[t.MAINVERSION] + src[t.PRERELEASE] + "?" + src[t.BUILD] + "?"; + src[t.FULL] = "^" + src[t.FULLPLAIN] + "$"; + tok("LOOSEPLAIN"); + src[t.LOOSEPLAIN] = "[v=\\s]*" + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + "?" + src[t.BUILD] + "?"; + tok("LOOSE"); + src[t.LOOSE] = "^" + src[t.LOOSEPLAIN] + "$"; + tok("GTLT"); + src[t.GTLT] = "((?:<|>)?=?)"; + tok("XRANGEIDENTIFIERLOOSE"); + src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + "|x|X|\\*"; + tok("XRANGEIDENTIFIER"); + src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + "|x|X|\\*"; + tok("XRANGEPLAIN"); + src[t.XRANGEPLAIN] = "[v=\\s]*(" + src[t.XRANGEIDENTIFIER] + ")(?:\\.(" + src[t.XRANGEIDENTIFIER] + ")(?:\\.(" + src[t.XRANGEIDENTIFIER] + ")(?:" + src[t.PRERELEASE] + ")?" + src[t.BUILD] + "?)?)?"; + tok("XRANGEPLAINLOOSE"); + src[t.XRANGEPLAINLOOSE] = "[v=\\s]*(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:" + src[t.PRERELEASELOOSE] + ")?" + src[t.BUILD] + "?)?)?"; + tok("XRANGE"); + src[t.XRANGE] = "^" + src[t.GTLT] + "\\s*" + src[t.XRANGEPLAIN] + "$"; + tok("XRANGELOOSE"); + src[t.XRANGELOOSE] = "^" + src[t.GTLT] + "\\s*" + src[t.XRANGEPLAINLOOSE] + "$"; + tok("COERCE"); + src[t.COERCE] = "(^|[^\\d])(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "})(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:$|[^\\d])"; + tok("COERCERTL"); + re[t.COERCERTL] = new RegExp(src[t.COERCE], "g"); + safeRe[t.COERCERTL] = new RegExp(makeSafeRe(src[t.COERCE]), "g"); + tok("LONETILDE"); + src[t.LONETILDE] = "(?:~>?)"; + tok("TILDETRIM"); + src[t.TILDETRIM] = "(\\s*)" + src[t.LONETILDE] + "\\s+"; + re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], "g"); + safeRe[t.TILDETRIM] = new RegExp(makeSafeRe(src[t.TILDETRIM]), "g"); + var tildeTrimReplace = "$1~"; + tok("TILDE"); + src[t.TILDE] = "^" + src[t.LONETILDE] + src[t.XRANGEPLAIN] + "$"; + tok("TILDELOOSE"); + src[t.TILDELOOSE] = "^" + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + "$"; + tok("LONECARET"); + src[t.LONECARET] = "(?:\\^)"; + tok("CARETTRIM"); + src[t.CARETTRIM] = "(\\s*)" + src[t.LONECARET] + "\\s+"; + re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], "g"); + safeRe[t.CARETTRIM] = new RegExp(makeSafeRe(src[t.CARETTRIM]), "g"); + var caretTrimReplace = "$1^"; + tok("CARET"); + src[t.CARET] = "^" + src[t.LONECARET] + src[t.XRANGEPLAIN] + "$"; + tok("CARETLOOSE"); + src[t.CARETLOOSE] = "^" + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + "$"; + tok("COMPARATORLOOSE"); + src[t.COMPARATORLOOSE] = "^" + src[t.GTLT] + "\\s*(" + src[t.LOOSEPLAIN] + ")$|^$"; + tok("COMPARATOR"); + src[t.COMPARATOR] = "^" + src[t.GTLT] + "\\s*(" + src[t.FULLPLAIN] + ")$|^$"; + tok("COMPARATORTRIM"); + src[t.COMPARATORTRIM] = "(\\s*)" + src[t.GTLT] + "\\s*(" + src[t.LOOSEPLAIN] + "|" + src[t.XRANGEPLAIN] + ")"; + re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], "g"); + safeRe[t.COMPARATORTRIM] = new RegExp(makeSafeRe(src[t.COMPARATORTRIM]), "g"); + var comparatorTrimReplace = "$1$2$3"; + tok("HYPHENRANGE"); + src[t.HYPHENRANGE] = "^\\s*(" + src[t.XRANGEPLAIN] + ")\\s+-\\s+(" + src[t.XRANGEPLAIN] + ")\\s*$"; + tok("HYPHENRANGELOOSE"); + src[t.HYPHENRANGELOOSE] = "^\\s*(" + src[t.XRANGEPLAINLOOSE] + ")\\s+-\\s+(" + src[t.XRANGEPLAINLOOSE] + ")\\s*$"; + tok("STAR"); + src[t.STAR] = "(<|>)?=?\\s*\\*"; + for (i = 0; i < R; i++) { + debug3(i, src[i]); + if (!re[i]) { + re[i] = new RegExp(src[i]); + safeRe[i] = new RegExp(makeSafeRe(src[i])); + } + } + var i; + exports2.parse = parse; + function parse(version, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (version instanceof SemVer) { + return version; + } + if (typeof version !== "string") { + return null; + } + if (version.length > MAX_LENGTH) { + return null; + } + var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]; + if (!r.test(version)) { + return null; + } + try { + return new SemVer(version, options); + } catch (er) { + return null; + } + } + exports2.valid = valid2; + function valid2(version, options) { + var v = parse(version, options); + return v ? v.version : null; + } + exports2.clean = clean; + function clean(version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ""), options); + return s ? s.version : null; + } + exports2.SemVer = SemVer; + function SemVer(version, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== "string") { + throw new TypeError("Invalid Version: " + version); + } + if (version.length > MAX_LENGTH) { + throw new TypeError("version is longer than " + MAX_LENGTH + " characters"); + } + if (!(this instanceof SemVer)) { + return new SemVer(version, options); + } + debug3("SemVer", version, options); + this.options = options; + this.loose = !!options.loose; + var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]); + if (!m) { + throw new TypeError("Invalid Version: " + version); + } + this.raw = version; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split(".").map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id; + }); + } + this.build = m[5] ? m[5].split(".") : []; + this.format(); + } + SemVer.prototype.format = function() { + this.version = this.major + "." + this.minor + "." + this.patch; + if (this.prerelease.length) { + this.version += "-" + this.prerelease.join("."); + } + return this.version; + }; + SemVer.prototype.toString = function() { + return this.version; + }; + SemVer.prototype.compare = function(other) { + debug3("SemVer.compare", this.version, this.options, other); + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + return this.compareMain(other) || this.comparePre(other); + }; + SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + }; + SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + var i2 = 0; + do { + var a = this.prerelease[i2]; + var b = other.prerelease[i2]; + debug3("prerelease compare", i2, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i2); + }; + SemVer.prototype.compareBuild = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + var i2 = 0; + do { + var a = this.build[i2]; + var b = other.build[i2]; + debug3("prerelease compare", i2, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i2); + }; + SemVer.prototype.inc = function(release3, identifier) { + switch (release3) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier); + this.inc("pre", identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier); + } + this.inc("pre", identifier); + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case "pre": + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + var i2 = this.prerelease.length; + while (--i2 >= 0) { + if (typeof this.prerelease[i2] === "number") { + this.prerelease[i2]++; + i2 = -2; + } + } + if (i2 === -1) { + this.prerelease.push(0); + } + } + if (identifier) { + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break; + default: + throw new Error("invalid increment argument: " + release3); + } + this.format(); + this.raw = this.version; + return this; + }; + exports2.inc = inc; + function inc(version, release3, loose, identifier) { + if (typeof loose === "string") { + identifier = loose; + loose = void 0; + } + try { + return new SemVer(version, loose).inc(release3, identifier).version; + } catch (er) { + return null; + } + } + exports2.diff = diff; + function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + var prefix = ""; + if (v1.prerelease.length || v2.prerelease.length) { + prefix = "pre"; + var defaultResult = "prerelease"; + } + for (var key in v1) { + if (key === "major" || key === "minor" || key === "patch") { + if (v1[key] !== v2[key]) { + return prefix + key; + } + } + } + return defaultResult; + } + } + exports2.compareIdentifiers = compareIdentifiers; + var numeric = /^[0-9]+$/; + function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + if (anum && bnum) { + a = +a; + b = +b; + } + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + } + exports2.rcompareIdentifiers = rcompareIdentifiers; + function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); + } + exports2.major = major; + function major(a, loose) { + return new SemVer(a, loose).major; + } + exports2.minor = minor; + function minor(a, loose) { + return new SemVer(a, loose).minor; + } + exports2.patch = patch; + function patch(a, loose) { + return new SemVer(a, loose).patch; + } + exports2.compare = compare; + function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); + } + exports2.compareLoose = compareLoose; + function compareLoose(a, b) { + return compare(a, b, true); + } + exports2.compareBuild = compareBuild; + function compareBuild(a, b, loose) { + var versionA = new SemVer(a, loose); + var versionB = new SemVer(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); + } + exports2.rcompare = rcompare; + function rcompare(a, b, loose) { + return compare(b, a, loose); + } + exports2.sort = sort; + function sort(list, loose) { + return list.sort(function(a, b) { + return exports2.compareBuild(a, b, loose); + }); + } + exports2.rsort = rsort; + function rsort(list, loose) { + return list.sort(function(a, b) { + return exports2.compareBuild(b, a, loose); + }); + } + exports2.gt = gt; + function gt(a, b, loose) { + return compare(a, b, loose) > 0; + } + exports2.lt = lt; + function lt(a, b, loose) { + return compare(a, b, loose) < 0; + } + exports2.eq = eq; + function eq(a, b, loose) { + return compare(a, b, loose) === 0; + } + exports2.neq = neq; + function neq(a, b, loose) { + return compare(a, b, loose) !== 0; + } + exports2.gte = gte3; + function gte3(a, b, loose) { + return compare(a, b, loose) >= 0; + } + exports2.lte = lte; + function lte(a, b, loose) { + return compare(a, b, loose) <= 0; + } + exports2.cmp = cmp; + function cmp(a, op, b, loose) { + switch (op) { + case "===": + if (typeof a === "object") + a = a.version; + if (typeof b === "object") + b = b.version; + return a === b; + case "!==": + if (typeof a === "object") + a = a.version; + if (typeof b === "object") + b = b.version; + return a !== b; + case "": + case "=": + case "==": + return eq(a, b, loose); + case "!=": + return neq(a, b, loose); + case ">": + return gt(a, b, loose); + case ">=": + return gte3(a, b, loose); + case "<": + return lt(a, b, loose); + case "<=": + return lte(a, b, loose); + default: + throw new TypeError("Invalid operator: " + op); + } + } + exports2.Comparator = Comparator; + function Comparator(comp, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + if (!(this instanceof Comparator)) { + return new Comparator(comp, options); + } + comp = comp.trim().split(/\s+/).join(" "); + debug3("comparator", comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } + debug3("comp", this); + } + var ANY = {}; + Comparator.prototype.parse = function(comp) { + var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; + var m = comp.match(r); + if (!m) { + throw new TypeError("Invalid comparator: " + comp); + } + this.operator = m[1] !== void 0 ? m[1] : ""; + if (this.operator === "=") { + this.operator = ""; + } + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + }; + Comparator.prototype.toString = function() { + return this.value; + }; + Comparator.prototype.test = function(version) { + debug3("Comparator.test", version, this.options.loose); + if (this.semver === ANY || version === ANY) { + return true; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + return cmp(version, this.operator, this.semver, this.options); + }; + Comparator.prototype.intersects = function(comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError("a Comparator is required"); + } + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + var rangeTmp; + if (this.operator === "") { + if (this.value === "") { + return true; + } + rangeTmp = new Range2(comp.value, options); + return satisfies2(this.value, rangeTmp, options); + } else if (comp.operator === "") { + if (comp.value === "") { + return true; + } + rangeTmp = new Range2(this.value, options); + return satisfies2(comp.semver, rangeTmp, options); + } + var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">"); + var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<"); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<="); + var oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && ((this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<")); + var oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && ((this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">")); + return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; + }; + exports2.Range = Range2; + function Range2(range, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (range instanceof Range2) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new Range2(range.raw, options); + } + } + if (range instanceof Comparator) { + return new Range2(range.value, options); + } + if (!(this instanceof Range2)) { + return new Range2(range, options); + } + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + this.raw = range.trim().split(/\s+/).join(" "); + this.set = this.raw.split("||").map(function(range2) { + return this.parseRange(range2.trim()); + }, this).filter(function(c) { + return c.length; + }); + if (!this.set.length) { + throw new TypeError("Invalid SemVer Range: " + this.raw); + } + this.format(); + } + Range2.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(" ").trim(); + }).join("||").trim(); + return this.range; + }; + Range2.prototype.toString = function() { + return this.range; + }; + Range2.prototype.parseRange = function(range) { + var loose = this.options.loose; + var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug3("hyphen replace", range); + range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace); + debug3("comparator trim", range, safeRe[t.COMPARATORTRIM]); + range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace); + range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace); + range = range.split(/\s+/).join(" "); + var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; + var set2 = range.split(" ").map(function(comp) { + return parseComparator(comp, this.options); + }, this).join(" ").split(/\s+/); + if (this.options.loose) { + set2 = set2.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set2 = set2.map(function(comp) { + return new Comparator(comp, this.options); + }, this); + return set2; + }; + Range2.prototype.intersects = function(range, options) { + if (!(range instanceof Range2)) { + throw new TypeError("a Range is required"); + } + return this.set.some(function(thisComparators) { + return isSatisfiable(thisComparators, options) && range.set.some(function(rangeComparators) { + return isSatisfiable(rangeComparators, options) && thisComparators.every(function(thisComparator) { + return rangeComparators.every(function(rangeComparator) { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + }; + function isSatisfiable(comparators, options) { + var result = true; + var remainingComparators = comparators.slice(); + var testComparator = remainingComparators.pop(); + while (result && remainingComparators.length) { + result = remainingComparators.every(function(otherComparator) { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); + } + return result; + } + exports2.toComparators = toComparators; + function toComparators(range, options) { + return new Range2(range, options).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(" ").trim().split(" "); + }); + } + function parseComparator(comp, options) { + debug3("comp", comp, options); + comp = replaceCarets(comp, options); + debug3("caret", comp); + comp = replaceTildes(comp, options); + debug3("tildes", comp); + comp = replaceXRanges(comp, options); + debug3("xrange", comp); + comp = replaceStars(comp, options); + debug3("stars", comp); + return comp; + } + function isX(id) { + return !id || id.toLowerCase() === "x" || id === "*"; + } + function replaceTildes(comp, options) { + return comp.trim().split(/\s+/).map(function(comp2) { + return replaceTilde(comp2, options); + }).join(" "); + } + function replaceTilde(comp, options) { + var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug3("tilde", comp, _, M, m, p, pr); + var ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; + } else if (isX(p)) { + ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; + } else if (pr) { + debug3("replaceTilde pr", pr); + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; + } else { + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; + } + debug3("tilde return", ret); + return ret; + }); + } + function replaceCarets(comp, options) { + return comp.trim().split(/\s+/).map(function(comp2) { + return replaceCaret(comp2, options); + }).join(" "); + } + function replaceCaret(comp, options) { + debug3("caret", comp, options); + var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug3("caret", comp, _, M, m, p, pr); + var ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; + } else if (isX(p)) { + if (M === "0") { + ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; + } else { + ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0"; + } + } else if (pr) { + debug3("replaceCaret pr", pr); + if (M === "0") { + if (m === "0") { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1); + } else { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; + } + } else { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0"; + } + } else { + debug3("no pr"); + if (M === "0") { + if (m === "0") { + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1); + } else { + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; + } + } else { + ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0"; + } + } + debug3("caret return", ret); + return ret; + }); + } + function replaceXRanges(comp, options) { + debug3("replaceXRanges", comp, options); + return comp.split(/\s+/).map(function(comp2) { + return replaceXRange(comp2, options); + }).join(" "); + } + function replaceXRange(comp, options) { + comp = comp.trim(); + var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug3("xRange", comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; + } else { + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + ret = gtlt + M + "." + m + "." + p + pr; + } else if (xm) { + ret = ">=" + M + ".0.0" + pr + " <" + (+M + 1) + ".0.0" + pr; + } else if (xp) { + ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr; + } + debug3("xRange return", ret); + return ret; + }); + } + function replaceStars(comp, options) { + debug3("replaceStars", comp, options); + return comp.trim().replace(safeRe[t.STAR], ""); + } + function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = ">=" + fM + ".0.0"; + } else if (isX(fp)) { + from = ">=" + fM + "." + fm + ".0"; + } else { + from = ">=" + from; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = "<" + (+tM + 1) + ".0.0"; + } else if (isX(tp)) { + to = "<" + tM + "." + (+tm + 1) + ".0"; + } else if (tpr) { + to = "<=" + tM + "." + tm + "." + tp + "-" + tpr; + } else { + to = "<=" + to; + } + return (from + " " + to).trim(); + } + Range2.prototype.test = function(version) { + if (!version) { + return false; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + for (var i2 = 0; i2 < this.set.length; i2++) { + if (testSet(this.set[i2], version, this.options)) { + return true; + } + } + return false; + }; + function testSet(set2, version, options) { + for (var i2 = 0; i2 < set2.length; i2++) { + if (!set2[i2].test(version)) { + return false; + } + } + if (version.prerelease.length && !options.includePrerelease) { + for (i2 = 0; i2 < set2.length; i2++) { + debug3(set2[i2].semver); + if (set2[i2].semver === ANY) { + continue; + } + if (set2[i2].semver.prerelease.length > 0) { + var allowed = set2[i2].semver; + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; + } + } + } + return false; + } + return true; + } + exports2.satisfies = satisfies2; + function satisfies2(version, range, options) { + try { + range = new Range2(range, options); + } catch (er) { + return false; + } + return range.test(version); + } + exports2.maxSatisfying = maxSatisfying; + function maxSatisfying(versions, range, options) { + var max = null; + var maxSV = null; + try { + var rangeObj = new Range2(range, options); + } catch (er) { + return null; + } + versions.forEach(function(v) { + if (rangeObj.test(v)) { + if (!max || maxSV.compare(v) === -1) { + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max; + } + exports2.minSatisfying = minSatisfying; + function minSatisfying(versions, range, options) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range2(range, options); + } catch (er) { + return null; + } + versions.forEach(function(v) { + if (rangeObj.test(v)) { + if (!min || minSV.compare(v) === 1) { + min = v; + minSV = new SemVer(min, options); + } + } + }); + return min; + } + exports2.minVersion = minVersion; + function minVersion(range, loose) { + range = new Range2(range, loose); + var minver = new SemVer("0.0.0"); + if (range.test(minver)) { + return minver; + } + minver = new SemVer("0.0.0-0"); + if (range.test(minver)) { + return minver; + } + minver = null; + for (var i2 = 0; i2 < range.set.length; ++i2) { + var comparators = range.set[i2]; + comparators.forEach(function(comparator) { + var compver = new SemVer(comparator.semver.version); + switch (comparator.operator) { + case ">": + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case "": + case ">=": + if (!minver || gt(minver, compver)) { + minver = compver; + } + break; + case "<": + case "<=": + break; + /* istanbul ignore next */ + default: + throw new Error("Unexpected operation: " + comparator.operator); + } + }); + } + if (minver && range.test(minver)) { + return minver; + } + return null; + } + exports2.validRange = validRange; + function validRange(range, options) { + try { + return new Range2(range, options).range || "*"; + } catch (er) { + return null; + } + } + exports2.ltr = ltr; + function ltr(version, range, options) { + return outside(version, range, "<", options); + } + exports2.gtr = gtr; + function gtr(version, range, options) { + return outside(version, range, ">", options); + } + exports2.outside = outside; + function outside(version, range, hilo, options) { + version = new SemVer(version, options); + range = new Range2(range, options); + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case ">": + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = ">"; + ecomp = ">="; + break; + case "<": + gtfn = lt; + ltefn = gte3; + ltfn = gt; + comp = "<"; + ecomp = "<="; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + if (satisfies2(version, range, options)) { + return false; + } + for (var i2 = 0; i2 < range.set.length; ++i2) { + var comparators = range.set[i2]; + var high = null; + var low = null; + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator(">=0.0.0"); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + if (high.operator === comp || high.operator === ecomp) { + return false; + } + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; + } + exports2.prerelease = prerelease; + function prerelease(version, options) { + var parsed = parse(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; + } + exports2.intersects = intersects; + function intersects(r1, r2, options) { + r1 = new Range2(r1, options); + r2 = new Range2(r2, options); + return r1.intersects(r2); + } + exports2.coerce = coerce2; + function coerce2(version, options) { + if (version instanceof SemVer) { + return version; + } + if (typeof version === "number") { + version = String(version); + } + if (typeof version !== "string") { + return null; + } + options = options || {}; + var match = null; + if (!options.rtl) { + match = version.match(safeRe[t.COERCE]); + } else { + var next; + while ((next = safeRe[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + safeRe[t.COERCERTL].lastIndex = -1; + } + if (match === null) { + return null; + } + return parse(match[2] + "." + (match[3] || "0") + "." + (match[4] || "0"), options); + } + } +}); + +// node_modules/@actions/cache/lib/internal/constants.js +var require_constants7 = __commonJS({ + "node_modules/@actions/cache/lib/internal/constants.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheFileSizeLimit = exports2.ManifestFilename = exports2.TarFilename = exports2.SystemTarPathOnWindows = exports2.GnuTarPathOnWindows = exports2.SocketTimeout = exports2.DefaultRetryDelay = exports2.DefaultRetryAttempts = exports2.ArchiveToolType = exports2.CompressionMethod = exports2.CacheFilename = void 0; + var CacheFilename; + (function(CacheFilename2) { + CacheFilename2["Gzip"] = "cache.tgz"; + CacheFilename2["Zstd"] = "cache.tzst"; + })(CacheFilename || (exports2.CacheFilename = CacheFilename = {})); + var CompressionMethod; + (function(CompressionMethod2) { + CompressionMethod2["Gzip"] = "gzip"; + CompressionMethod2["ZstdWithoutLong"] = "zstd-without-long"; + CompressionMethod2["Zstd"] = "zstd"; + })(CompressionMethod || (exports2.CompressionMethod = CompressionMethod = {})); + var ArchiveToolType; + (function(ArchiveToolType2) { + ArchiveToolType2["GNU"] = "gnu"; + ArchiveToolType2["BSD"] = "bsd"; + })(ArchiveToolType || (exports2.ArchiveToolType = ArchiveToolType = {})); + exports2.DefaultRetryAttempts = 2; + exports2.DefaultRetryDelay = 5e3; + exports2.SocketTimeout = 5e3; + exports2.GnuTarPathOnWindows = `${process.env["PROGRAMFILES"]}\\Git\\usr\\bin\\tar.exe`; + exports2.SystemTarPathOnWindows = `${process.env["SYSTEMDRIVE"]}\\Windows\\System32\\tar.exe`; + exports2.TarFilename = "cache.tar"; + exports2.ManifestFilename = "manifest.txt"; + exports2.CacheFileSizeLimit = 10 * Math.pow(1024, 3); + } +}); + +// node_modules/@actions/cache/lib/internal/cacheUtils.js +var require_cacheUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/cacheUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __asyncValues4 = exports2 && exports2.__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(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRuntimeToken = exports2.getCacheVersion = exports2.assertDefined = exports2.getGnuTarPathOnWindows = exports2.getCacheFileName = exports2.getCompressionMethod = exports2.unlinkFile = exports2.resolvePaths = exports2.getArchiveFileSizeInBytes = exports2.createTempDirectory = void 0; + var core12 = __importStar4(require_core()); + var exec2 = __importStar4(require_exec()); + var glob = __importStar4(require_glob()); + var io4 = __importStar4(require_io()); + var crypto = __importStar4(require("crypto")); + var fs = __importStar4(require("fs")); + var path2 = __importStar4(require("path")); + var semver5 = __importStar4(require_semver3()); + var util = __importStar4(require("util")); + var constants_1 = require_constants7(); + var versionSalt = "1.0"; + function createTempDirectory() { + return __awaiter4(this, void 0, void 0, function* () { + const IS_WINDOWS = process.platform === "win32"; + let tempDirectory = process.env["RUNNER_TEMP"] || ""; + if (!tempDirectory) { + let baseLocation; + if (IS_WINDOWS) { + baseLocation = process.env["USERPROFILE"] || "C:\\"; + } else { + if (process.platform === "darwin") { + baseLocation = "/Users"; + } else { + baseLocation = "/home"; + } + } + tempDirectory = path2.join(baseLocation, "actions", "temp"); + } + const dest = path2.join(tempDirectory, crypto.randomUUID()); + yield io4.mkdirP(dest); + return dest; + }); + } + exports2.createTempDirectory = createTempDirectory; + function getArchiveFileSizeInBytes(filePath) { + return fs.statSync(filePath).size; + } + exports2.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; + function resolvePaths(patterns) { + var _a, e_1, _b, _c; + var _d; + return __awaiter4(this, void 0, void 0, function* () { + const paths = []; + const workspace = (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); + const globber = yield glob.create(patterns.join("\n"), { + implicitDescendants: false + }); + try { + for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { + _c = _g.value; + _e = false; + const file = _c; + const relativeFile = path2.relative(workspace, file).replace(new RegExp(`\\${path2.sep}`, "g"), "/"); + core12.debug(`Matched: ${relativeFile}`); + if (relativeFile === "") { + paths.push("."); + } else { + paths.push(`${relativeFile}`); + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); + } finally { + if (e_1) throw e_1.error; + } + } + return paths; + }); + } + exports2.resolvePaths = resolvePaths; + function unlinkFile(filePath) { + return __awaiter4(this, void 0, void 0, function* () { + return util.promisify(fs.unlink)(filePath); + }); + } + exports2.unlinkFile = unlinkFile; + function getVersion(app, additionalArgs = []) { + return __awaiter4(this, void 0, void 0, function* () { + let versionOutput = ""; + additionalArgs.push("--version"); + core12.debug(`Checking ${app} ${additionalArgs.join(" ")}`); + try { + yield exec2.exec(`${app}`, additionalArgs, { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + } catch (err) { + core12.debug(err.message); + } + versionOutput = versionOutput.trim(); + core12.debug(versionOutput); + return versionOutput; + }); + } + function getCompressionMethod() { + return __awaiter4(this, void 0, void 0, function* () { + const versionOutput = yield getVersion("zstd", ["--quiet"]); + const version = semver5.clean(versionOutput); + core12.debug(`zstd version: ${version}`); + if (versionOutput === "") { + return constants_1.CompressionMethod.Gzip; + } else { + return constants_1.CompressionMethod.ZstdWithoutLong; + } + }); + } + exports2.getCompressionMethod = getCompressionMethod; + function getCacheFileName(compressionMethod) { + return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd; + } + exports2.getCacheFileName = getCacheFileName; + function getGnuTarPathOnWindows() { + return __awaiter4(this, void 0, void 0, function* () { + if (fs.existsSync(constants_1.GnuTarPathOnWindows)) { + return constants_1.GnuTarPathOnWindows; + } + const versionOutput = yield getVersion("tar"); + return versionOutput.toLowerCase().includes("gnu tar") ? io4.which("tar") : ""; + }); + } + exports2.getGnuTarPathOnWindows = getGnuTarPathOnWindows; + function assertDefined(name, value) { + if (value === void 0) { + throw Error(`Expected ${name} but value was undefiend`); + } + return value; + } + exports2.assertDefined = assertDefined; + function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) { + const components = paths.slice(); + if (compressionMethod) { + components.push(compressionMethod); + } + if (process.platform === "win32" && !enableCrossOsArchive) { + components.push("windows-only"); + } + components.push(versionSalt); + return crypto.createHash("sha256").update(components.join("|")).digest("hex"); + } + exports2.getCacheVersion = getCacheVersion; + function getRuntimeToken() { + const token = process.env["ACTIONS_RUNTIME_TOKEN"]; + if (!token) { + throw new Error("Unable to get the ACTIONS_RUNTIME_TOKEN env variable"); + } + return token; + } + exports2.getRuntimeToken = getRuntimeToken; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; + } + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; + } + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } + }; + function createEmptyPipeline() { + return HttpPipeline.create(); + } + } +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os2 = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; + } + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os2.EOL}`); + } + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); + } + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } + } + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; + } + function disable() { + const result = enabledString || ""; + enable(""); + return result; + } + function createDebugger(namespace) { + const newDebugger = Object.assign(debug4, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug4(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; + } + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug3 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug3("azure"); + AzureLogger.log = (...args) => { + debug3.log(...args); + }; + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } + } + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); + } + } + debug3.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 + }; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; + } + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug3.disable(); + debug3.enable(enabledNamespaces2 + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; + } + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); + } + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError; + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve2, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve2(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay2; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random2(); + var StandardAbortMessage = "The delay was aborted."; + function delay2(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve2) => { + token = setTimeout(resolve2, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage + }); + } + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); + } + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; + } + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; + } else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha2562 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + } + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { + "use strict"; + var _a; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.randomUUID = randomUUID; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID() { + return uuidFunction(); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { + "use strict"; + var _a; + var _b; + var _c; + var _d; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); + } + function stringToUint8Array(value, format) { + return Buffer.from(value, format); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random2(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha2562(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Sanitizer = void 0; + var core_util_1 = require_commonjs2(); + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); + } + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; + } + const url = new URL(value); + if (!url.search) { + return value; + } + for (const [key] of url.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url.searchParams.set(key, RedactedString); + } + } + return url.toString(); + } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + }; + exports2.Sanitizer = Sanitizer; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log2(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + return { + name: exports2.logPolicyName, + async sendRequest(request, next) { + if (!logger.enabled) { + return next(request); + } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; + return { + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + } + }; + } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url = new URL(locationHeader, request.url); + request.url = url.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; + } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); + } + return response; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values2, + default: () => tslib_es6_default +}); +function __extends(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 __()); +} +function __rest(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; +} +function __decorate(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; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(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 context2 = {}; + for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; + context2.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], context2); + 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.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(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; +} +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName(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 }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["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 (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]) { + 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 }; + } +} +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} +function __values2(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."); +} +function __read(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 (error2) { + e = { error: error2 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} +function __spreadArrays() { + 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; +} +function __spreadArray(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)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + 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]); + } +} +function __asyncDelegator(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 __asyncValues(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 __values2 === "function" ? __values2(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(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(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; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(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); +} +function __classPrivateFieldSet(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; +} +function __classPrivateFieldIn(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); +} +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; +var init_tslib_es6 = __esm({ + "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + __assign = function() { + __assign = Object.assign || function __assign4(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; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error2, e.suppressed = suppressed, e; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values: __values2, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources + }; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js +var require_userAgentPlatform = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getHeaderName = getHeaderName; + exports2.setPlatformSpecificData = setPlatformSpecificData; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var os2 = tslib_1.__importStar(require("node:os")); + var process2 = tslib_1.__importStar(require("node:process")); + function getHeaderName() { + return "User-Agent"; + } + async function setPlatformSpecificData(map2) { + if (process2 && process2.versions) { + const versions = process2.versions; + if (versions.bun) { + map2.set("Bun", versions.bun); + } else if (versions.deno) { + map2.set("Deno", versions.deno); + } else if (versions.node) { + map2.set("Node", versions.node); + } + } + map2.set("OS", `(${os2.arch()}-${os2.type()}-${os2.release()})`); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js +var require_constants8 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; + exports2.SDK_VERSION = "1.17.0"; + exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js +var require_userAgent = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getUserAgentHeaderName = getUserAgentHeaderName; + exports2.getUserAgentValue = getUserAgentValue; + var userAgentPlatform_js_1 = require_userAgentPlatform(); + var constants_js_1 = require_constants8(); + function getUserAgentString(telemetryInfo) { + const parts = []; + for (const [key, value] of telemetryInfo) { + const token = value ? `${key}/${value}` : key; + parts.push(token); + } + return parts.join(" "); + } + function getUserAgentHeaderName() { + return (0, userAgentPlatform_js_1.getHeaderName)(); + } + async function getUserAgentValue(prefix) { + const runtimeInfo = /* @__PURE__ */ new Map(); + runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); + await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); + const defaultAgent = getUserAgentString(runtimeInfo); + const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; + return userAgentValue; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js +var require_userAgentPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.userAgentPolicyName = void 0; + exports2.userAgentPolicy = userAgentPolicy; + var userAgent_js_1 = require_userAgent(); + var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); + exports2.userAgentPolicyName = "userAgentPolicy"; + function userAgentPolicy(options = {}) { + const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + return { + name: exports2.userAgentPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(UserAgentHeaderName)) { + request.headers.set(UserAgentHeaderName, await userAgentValue); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js +var require_typeGuards2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isNodeReadableStream = isNodeReadableStream; + exports2.isWebReadableStream = isWebReadableStream; + exports2.isReadableStream = isReadableStream; + exports2.isBlob = isBlob; + function isNodeReadableStream(x) { + return Boolean(x && typeof x["pipe"] === "function"); + } + function isWebReadableStream(x) { + return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); + } + function isReadableStream(x) { + return isNodeReadableStream(x) || isWebReadableStream(x); + } + function isBlob(x) { + return typeof x.stream === "function"; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js +var require_file2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRawContent = getRawContent; + exports2.createFileFromStream = createFileFromStream; + exports2.createFile = createFile; + var core_util_1 = require_commonjs2(); + var typeGuards_js_1 = require_typeGuards2(); + var unimplementedMethods = { + arrayBuffer: () => { + throw new Error("Not implemented"); + }, + slice: () => { + throw new Error("Not implemented"); + }, + text: () => { + throw new Error("Not implemented"); + } + }; + var rawContent = Symbol("rawContent"); + function hasRawContent(x) { + return typeof x[rawContent] === "function"; + } + function getRawContent(blob) { + if (hasRawContent(blob)) { + return blob[rawContent](); + } else { + return blob.stream(); + } + } + function createFileFromStream(stream, name, options = {}) { + var _a, _b, _c, _d; + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { + const s = stream(); + if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { + throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); + } + return s; + }, [rawContent]: stream }); + } + function createFile(content, name, options = {}) { + var _a, _b, _c; + if (core_util_1.isNodeLike) { + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); + } else { + return new File([content], name, options); + } + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js +var require_concat = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.concat = concat; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var node_stream_1 = require("node:stream"); + var typeGuards_js_1 = require_typeGuards2(); + var file_js_1 = require_file2(); + function streamAsyncIterator() { + return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { + const reader = this.getReader(); + try { + while (true) { + const { done, value } = yield tslib_1.__await(reader.read()); + if (done) { + return yield tslib_1.__await(void 0); + } + yield yield tslib_1.__await(value); + } + } finally { + reader.releaseLock(); + } + }); + } + function makeAsyncIterable(webStream) { + if (!webStream[Symbol.asyncIterator]) { + webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); + } + if (!webStream.values) { + webStream.values = streamAsyncIterator.bind(webStream); + } + } + function ensureNodeStream(stream) { + if (stream instanceof ReadableStream) { + makeAsyncIterable(stream); + return node_stream_1.Readable.fromWeb(stream); + } else { + return stream; + } + } + function toStream(source) { + if (source instanceof Uint8Array) { + return node_stream_1.Readable.from(Buffer.from(source)); + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return toStream((0, file_js_1.getRawContent)(source)); + } else { + return ensureNodeStream(source); + } + } + async function concat(sources) { + return function() { + const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); + return node_stream_1.Readable.from((function() { + return tslib_1.__asyncGenerator(this, arguments, function* () { + var _a, e_1, _b, _c; + for (const stream of streams) { + try { + for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { + _c = stream_1_1.value; + _d = false; + const chunk = _c; + yield yield tslib_1.__await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); + } finally { + if (e_1) throw e_1.error; + } + } + } + }); + })()); + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js +var require_multipartPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.multipartPolicyName = void 0; + exports2.multipartPolicy = multipartPolicy; + var core_util_1 = require_commonjs2(); + var concat_js_1 = require_concat(); + var typeGuards_js_1 = require_typeGuards2(); + function generateBoundary() { + return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; + } + function encodeHeaders(headers) { + let result = ""; + for (const [key, value] of headers) { + result += `${key}: ${value}\r +`; + } + return result; + } + function getLength(source) { + if (source instanceof Uint8Array) { + return source.byteLength; + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return source.size === -1 ? void 0 : source.size; + } else { + return void 0; + } + } + function getTotalLength(sources) { + let total = 0; + for (const source of sources) { + const partLength = getLength(source); + if (partLength === void 0) { + return void 0; + } else { + total += partLength; + } + } + return total; + } + async function buildRequestBody(request, parts, boundary) { + const sources = [ + (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), + ...parts.flatMap((part) => [ + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + part.body, + (0, core_util_1.stringToUint8Array)(`\r +--${boundary}`, "utf-8") + ]), + (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") + ]; + const contentLength = getTotalLength(sources); + if (contentLength) { + request.headers.set("Content-Length", contentLength); + } + request.body = await (0, concat_js_1.concat)(sources); + } + exports2.multipartPolicyName = "multipartPolicy"; + var maxBoundaryLength = 70; + var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); + function assertValidBoundary(boundary) { + if (boundary.length > maxBoundaryLength) { + throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); + } + if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { + throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); + } + } + function multipartPolicy() { + return { + name: exports2.multipartPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.multipartBody) { + return next(request); + } + if (request.body) { + throw new Error("multipartBody and regular body cannot be set at the same time"); + } + let boundary = request.multipartBody.boundary; + const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; + const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); + if (!parsedHeader) { + throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); + } + const [, contentType, parsedBoundary] = parsedHeader; + if (parsedBoundary && boundary && parsedBoundary !== boundary) { + throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); + } + boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; + if (boundary) { + assertValidBoundary(boundary); + } else { + boundary = generateBoundary(); + } + request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); + await buildRequestBody(request, request.multipartBody.parts, boundary); + request.multipartBody = void 0; + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js +var require_decompressResponsePolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decompressResponsePolicyName = void 0; + exports2.decompressResponsePolicy = decompressResponsePolicy; + exports2.decompressResponsePolicyName = "decompressResponsePolicy"; + function decompressResponsePolicy() { + return { + name: exports2.decompressResponsePolicyName, + async sendRequest(request, next) { + if (request.method !== "HEAD") { + request.headers.set("Accept-Encoding", "gzip,deflate"); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError; + } +}); + +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs3 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError2(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js +var require_helpers = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay2; + exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; + var abort_controller_1 = require_commonjs3(); + var StandardAbortMessage = "The operation was aborted."; + function delay2(delayInMs, value, options) { + return new Promise((resolve2, reject) => { + let timer = void 0; + let onAborted = void 0; + const rejectOnAbort = () => { + return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); + } + }; + onAborted = () => { + if (timer) { + clearTimeout(timer); + } + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve2(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); + } + }); + } + function parseHeaderValueAsNumber(response, headerName) { + const value = response.headers.get(headerName); + if (!value) + return; + const valueAsNum = Number(value); + if (Number.isNaN(valueAsNum)) + return; + return valueAsNum; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js +var require_throttlingRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; + exports2.throttlingRetryStrategy = throttlingRetryStrategy; + var helpers_js_1 = require_helpers(); + var RetryAfterHeader = "Retry-After"; + var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; + function getRetryAfterInMs(response) { + if (!(response && [429, 503].includes(response.status))) + return void 0; + try { + for (const header of AllRetryAfterHeaders) { + const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); + if (retryAfterValue === 0 || retryAfterValue) { + const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; + return retryAfterValue * multiplyingFactor; + } + } + const retryAfterHeader = response.headers.get(RetryAfterHeader); + if (!retryAfterHeader) + return; + const date = Date.parse(retryAfterHeader); + const diff = date - Date.now(); + return Number.isFinite(diff) ? Math.max(0, diff) : void 0; + } catch (_a) { + return void 0; + } + } + function isThrottlingRetryResponse(response) { + return Number.isFinite(getRetryAfterInMs(response)); + } + function throttlingRetryStrategy() { + return { + name: "throttlingRetryStrategy", + retry({ response }) { + const retryAfterInMs = getRetryAfterInMs(response); + if (!Number.isFinite(retryAfterInMs)) { + return { skipStrategy: true }; + } + return { + retryAfterInMs + }; + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js +var require_exponentialRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.exponentialRetryStrategy = exponentialRetryStrategy; + exports2.isExponentialRetryResponse = isExponentialRetryResponse; + exports2.isSystemError = isSystemError; + var core_util_1 = require_commonjs2(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; + var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; + function exponentialRetryStrategy(options = {}) { + var _a, _b; + const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + let retryAfterInMs = retryInterval; + return { + name: "exponentialRetryStrategy", + retry({ retryCount, response, responseError }) { + const matchedSystemError = isSystemError(responseError); + const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; + const isExponential = isExponentialRetryResponse(response); + const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; + const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); + if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { + return { skipStrategy: true }; + } + if (responseError && !matchedSystemError && !isExponential) { + return { errorToThrow: responseError }; + } + const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); + const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); + retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); + return { retryAfterInMs }; + } + }; + } + function isExponentialRetryResponse(response) { + return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); + } + function isSystemError(err) { + if (!err) { + return false; + } + return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js +var require_retryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.retryPolicy = retryPolicy; + var helpers_js_1 = require_helpers(); + var logger_1 = require_dist(); + var abort_controller_1 = require_commonjs3(); + var constants_js_1 = require_constants8(); + var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); + var retryPolicyName = "retryPolicy"; + function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { + const logger = options.logger || retryPolicyLogger; + return { + name: retryPolicyName, + async sendRequest(request, next) { + var _a, _b; + let response; + let responseError; + let retryCount = -1; + retryRequest: while (true) { + retryCount += 1; + response = void 0; + responseError = void 0; + try { + logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); + response = await next(request); + logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); + } catch (e) { + logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); + responseError = e; + if (!e || responseError.name !== "RestError") { + throw e; + } + response = responseError.response; + } + if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + logger.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new abort_controller_1.AbortError(); + throw abortError; + } + if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { + logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (responseError) { + throw responseError; + } else if (response) { + return response; + } else { + throw new Error("Maximum retries reached with no response or error to throw"); + } + } + logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + strategiesLoop: for (const strategy of strategies) { + const strategyLogger = strategy.logger || retryPolicyLogger; + strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); + const modifiers = strategy.retry({ + retryCount, + response, + responseError + }); + if (modifiers.skipStrategy) { + strategyLogger.info(`Retry ${retryCount}: Skipped.`); + continue strategiesLoop; + } + const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; + if (errorToThrow) { + strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + throw errorToThrow; + } + if (retryAfterInMs || retryAfterInMs === 0) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); + await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); + continue retryRequest; + } + if (redirectTo) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + request.url = redirectTo; + continue retryRequest; + } + } + if (responseError) { + logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + throw responseError; + } + if (response) { + logger.info(`None of the retry strategies could work with the received response. Returning it.`); + return response; + } + } + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js +var require_defaultRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.defaultRetryPolicyName = void 0; + exports2.defaultRetryPolicy = defaultRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.defaultRetryPolicyName = "defaultRetryPolicy"; + function defaultRetryPolicy(options = {}) { + var _a; + return { + name: exports2.defaultRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js +var require_httpHeaders = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createHttpHeaders = createHttpHeaders; + function normalizeName(name) { + return name.toLowerCase(); + } + function* headerIterator(map2) { + for (const entry of map2.values()) { + yield [entry.name, entry.value]; + } + } + var HttpHeadersImpl = class { + constructor(rawHeaders) { + this._headersMap = /* @__PURE__ */ new Map(); + if (rawHeaders) { + for (const headerName of Object.keys(rawHeaders)) { + this.set(headerName, rawHeaders[headerName]); + } + } + } + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param name - The name of the header to set. This value is case-insensitive. + * @param value - The value of the header to set. + */ + set(name, value) { + this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); + } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param name - The name of the header. This value is case-insensitive. + */ + get(name) { + var _a; + return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; + } + /** + * Get whether or not this header collection contains a header entry for the provided header name. + * @param name - The name of the header to set. This value is case-insensitive. + */ + has(name) { + return this._headersMap.has(normalizeName(name)); + } + /** + * Remove the header with the provided headerName. + * @param name - The name of the header to remove. + */ + delete(name) { + this._headersMap.delete(normalizeName(name)); + } + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJSON(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const entry of this._headersMap.values()) { + result[entry.name] = entry.value; + } + } else { + for (const [normalizedName, entry] of this._headersMap) { + result[normalizedName] = entry.value; + } + } + return result; + } + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJSON({ preserveCase: true })); + } + /** + * Iterate over tuples of header [name, value] pairs. + */ + [Symbol.iterator]() { + return headerIterator(this._headersMap); + } + }; + function createHttpHeaders(rawHeaders) { + return new HttpHeadersImpl(rawHeaders); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js +var require_formDataPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.formDataPolicyName = void 0; + exports2.formDataPolicy = formDataPolicy; + var core_util_1 = require_commonjs2(); + var httpHeaders_js_1 = require_httpHeaders(); + exports2.formDataPolicyName = "formDataPolicy"; + function formDataToFormDataMap(formData) { + var _a; + const formDataMap = {}; + for (const [key, value] of formData.entries()) { + (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; + formDataMap[key].push(value); + } + return formDataMap; + } + function formDataPolicy() { + return { + name: exports2.formDataPolicyName, + async sendRequest(request, next) { + if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { + request.formData = formDataToFormDataMap(request.body); + request.body = void 0; + } + if (request.formData) { + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = wwwFormUrlEncode(request.formData); + } else { + await prepareFormData(request.formData, request); + } + request.formData = void 0; + } + return next(request); + } + }; + } + function wwwFormUrlEncode(formData) { + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(formData)) { + if (Array.isArray(value)) { + for (const subValue of value) { + urlSearchParams.append(key, subValue.toString()); + } + } else { + urlSearchParams.append(key, value.toString()); + } + } + return urlSearchParams.toString(); + } + async function prepareFormData(formData, request) { + const contentType = request.headers.get("Content-Type"); + if (contentType && !contentType.startsWith("multipart/form-data")) { + return; + } + request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); + const parts = []; + for (const [fieldName, values] of Object.entries(formData)) { + for (const value of Array.isArray(values) ? values : [values]) { + if (typeof value === "string") { + parts.push({ + headers: (0, httpHeaders_js_1.createHttpHeaders)({ + "Content-Disposition": `form-data; name="${fieldName}"` + }), + body: (0, core_util_1.stringToUint8Array)(value, "utf-8") + }); + } else if (value === void 0 || value === null || typeof value !== "object") { + throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); + } else { + const fileName = value.name || "blob"; + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); + headers.set("Content-Type", value.type || "application/octet-stream"); + parts.push({ + headers, + body: value + }); + } + } + } + request.multipartBody = { parts }; + } + } +}); + +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports2, module2) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module2.exports = function(val2, options) { + options = options || {}; + var type2 = typeof val2; + if (type2 === "string" && val2.length > 0) { + return parse(val2); + } else if (type2 === "number" && isFinite(val2)) { + return options.long ? fmtLong(val2) : fmtShort(val2); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) + ); + }; + function parse(str2) { + str2 = String(str2); + if (str2.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str2 + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type2 = (match[2] || "ms").toLowerCase(); + switch (type2) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/debug/src/common.js"(exports2, module2) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce2; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug3(...args) { + if (!debug3.enabled) { + return; + } + const self2 = debug3; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val2 = args[index]; + match = formatter.call(self2, val2); + args.splice(index, 1); + index--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug3.namespace = namespace; + debug3.useColors = createDebug.useColors(); + debug3.color = createDebug.selectColor(namespace); + debug3.extend = extend3; + debug3.destroy = createDebug.destroy; + Object.defineProperty(debug3, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug3); + } + return debug3; + } + function extend3(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } + return false; + } + function coerce2(val2) { + if (val2 instanceof Error) { + return val2.stack || val2.message; + } + return val2; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module2.exports = setup; + } +}); + +// node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/debug/src/browser.js"(exports2, module2) { + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports2.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index++; + if (match === "%c") { + lastC = index; + } + }); + args.splice(lastC, 0, c); + } + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error2) { + } + } + function load2() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error2) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error2) { + } + } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error2) { + return "[UnexpectedJSONParseError]: " + error2.message; + } + }; + } +}); + +// node_modules/has-flag/index.js +var require_has_flag = __commonJS({ + "node_modules/has-flag/index.js"(exports2, module2) { + "use strict"; + module2.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; + } +}); + +// node_modules/supports-color/index.js +var require_supports_color = __commonJS({ + "node_modules/supports-color/index.js"(exports2, module2) { + "use strict"; + var os2 = require("os"); + var tty = require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + forceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = 1; + } + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + forceColor = 1; + } else if (env.FORCE_COLOR === "false") { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; + } + if (hasFlag("color=256")) { + return 2; + } + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os2.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { + return 1; + } + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); + } + module2.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; + } +}); + +// node_modules/debug/src/node.js +var require_node = __commonJS({ + "node_modules/debug/src/node.js"(exports2, module2) { + var tty = require("tty"); + var util = require("util"); + exports2.init = init; + exports2.log = log; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.destroy = util.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports2.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports2.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error2) { + } + exports2.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + let val2 = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val2)) { + val2 = true; + } else if (/^(no|off|false|disabled)$/i.test(val2)) { + val2 = false; + } else if (val2 === "null") { + val2 = null; + } else { + val2 = Number(val2); + } + obj[prop] = val2; + return obj; + }, {}); + function useColors() { + return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; + } + } + function getDate() { + if (exports2.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log(...args) { + return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load2() { + return process.env.DEBUG; + } + function init(debug3) { + debug3.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug3.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + } + } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; + } +}); + +// node_modules/debug/src/index.js +var require_src = __commonJS({ + "node_modules/debug/src/index.js"(exports2, module2) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module2.exports = require_browser(); + } else { + module2.exports = require_node(); + } + } +}); + +// node_modules/agent-base/dist/helpers.js +var require_helpers2 = __commonJS({ + "node_modules/agent-base/dist/helpers.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.req = exports2.json = exports2.toBuffer = void 0; + var http = __importStar4(require("http")); + var https = __importStar4(require("https")); + async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); + } + exports2.toBuffer = toBuffer; + async function json2(stream) { + const buf = await toBuffer(stream); + const str2 = buf.toString("utf8"); + try { + return JSON.parse(str2); + } catch (_err) { + const err = _err; + err.message += ` (input: ${str2})`; + throw err; + } + } + exports2.json = json2; + function req(url, opts = {}) { + const href = typeof url === "string" ? url : url.href; + const req2 = (href.startsWith("https:") ? https : http).request(url, opts); + const promise = new Promise((resolve2, reject) => { + req2.once("response", resolve2).once("error", reject).end(); + }); + req2.then = promise.then.bind(promise); + return req2; + } + exports2.req = req; + } +}); + +// node_modules/agent-base/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/agent-base/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Agent = void 0; + var net = __importStar4(require("net")); + var http = __importStar4(require("http")); + var https_1 = require("https"); + __exportStar4(require_helpers2(), exports2); + var INTERNAL = Symbol("AgentBaseInternalState"); + var Agent = class extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; + } + if (typeof options.protocol === "string") { + return options.protocol === "https:"; + } + } + const { stack } = new Error(); + if (typeof stack !== "string") + return false; + return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + if (!this.sockets[name]) { + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + this.totalSocketCount--; + if (sockets.length === 0) { + delete this.sockets[name]; + } + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); + if (secureEndpoint) { + return https_1.Agent.prototype.getName.call(this, options); + } + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + return socket.addRequest(req, connectOpts); + } catch (err) { + return cb(err); + } + } + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = void 0; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); + } + return socket; + } + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } + }; + exports2.Agent = Agent; + } +}); + +// node_modules/https-proxy-agent/dist/parse-proxy-response.js +var require_parse_proxy_response = __commonJS({ + "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { + "use strict"; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.parseProxyResponse = void 0; + var debug_1 = __importDefault4(require_src()); + var debug3 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse(socket) { + return new Promise((resolve2, reject) => { + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once("readable", read); + } + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read); + } + function onend() { + cleanup(); + debug3("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); + } + function onerror(err) { + cleanup(); + debug3("onerror %o", err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf("\r\n\r\n"); + if (endOfHeaders === -1) { + debug3("have not received end of HTTP headers yet..."); + read(); + return; + } + const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debug3("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve2({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); + } + socket.on("error", onerror); + socket.on("end", onend); + read(); + }); + } + exports2.parseProxyResponse = parseProxyResponse; + } +}); + +// node_modules/https-proxy-agent/dist/index.js +var require_dist3 = __commonJS({ + "node_modules/https-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpsProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var assert_1 = __importDefault4(require("assert")); + var debug_1 = __importDefault4(require_src()); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var parse_proxy_response_1 = require_parse_proxy_response(); + var debug3 = (0, debug_1.default)("https-proxy-agent"); + var setServernameFromNonIpHost = (options) => { + if (options.servername === void 0 && options.host && !net.isIP(options.host)) { + return { + ...options, + servername: options.host + }; + } + return options; + }; + var HttpsProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: void 0 }; + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug3("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ["http/1.1"], + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + let socket; + if (proxy.protocol === "https:") { + debug3("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } else { + debug3("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug3("Upgrading socket connection to TLS"); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), + socket + }); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug3("Replaying proxy buffer for failed request"); + (0, assert_1.default)(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } + }; + HttpsProxyAgent.protocols = ["http", "https"]; + exports2.HttpsProxyAgent = HttpsProxyAgent; + function resume(socket) { + socket.resume(); + } + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + } +}); + +// node_modules/http-proxy-agent/dist/index.js +var require_dist4 = __commonJS({ + "node_modules/http-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var debug_1 = __importDefault4(require_src()); + var events_1 = require("events"); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var debug3 = (0, debug_1.default)("http-proxy-agent"); + var HttpProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug3("Creating new HttpProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? "https:" : "http:"; + const hostname = req.getHeader("host") || "localhost"; + const base = `${protocol}//${hostname}`; + const url = new url_1.URL(req.path, base); + if (opts.port !== 80) { + url.port = String(opts.port); + } + req.path = String(url); + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + const value = headers[name]; + if (value) { + req.setHeader(name, value); + } + } + } + async connect(req, opts) { + req._header = null; + if (!req.path.includes("://")) { + this.setRequestProps(req, opts); + } + let first; + let endOfHeaders; + debug3("Regenerating stored HTTP header string for request"); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug3("Patching connection write() output buffer with updated header"); + first = req.outputData[0].data; + endOfHeaders = first.indexOf("\r\n\r\n") + 4; + req.outputData[0].data = req._header + first.substring(endOfHeaders); + debug3("Output buffer: %o", req.outputData[0].data); + } + let socket; + if (this.proxy.protocol === "https:") { + debug3("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(this.connectOpts); + } else { + debug3("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + await (0, events_1.once)(socket, "connect"); + return socket; + } + }; + HttpProxyAgent.protocols = ["http", "https"]; + exports2.HttpProxyAgent = HttpProxyAgent; + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js +var require_proxyPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; + exports2.loadNoProxy = loadNoProxy; + exports2.getDefaultProxySettings = getDefaultProxySettings; + exports2.proxyPolicy = proxyPolicy; + var https_proxy_agent_1 = require_dist3(); + var http_proxy_agent_1 = require_dist4(); + var log_js_1 = require_log2(); + var HTTPS_PROXY = "HTTPS_PROXY"; + var HTTP_PROXY = "HTTP_PROXY"; + var ALL_PROXY = "ALL_PROXY"; + var NO_PROXY = "NO_PROXY"; + exports2.proxyPolicyName = "proxyPolicy"; + exports2.globalNoProxyList = []; + var noProxyListLoaded = false; + var globalBypassedMap = /* @__PURE__ */ new Map(); + function getEnvironmentValue(name) { + if (process.env[name]) { + return process.env[name]; + } else if (process.env[name.toLowerCase()]) { + return process.env[name.toLowerCase()]; + } + return void 0; + } + function loadEnvironmentProxyValue() { + if (!process) { + return void 0; + } + const httpsProxy = getEnvironmentValue(HTTPS_PROXY); + const allProxy = getEnvironmentValue(ALL_PROXY); + const httpProxy = getEnvironmentValue(HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; + } + function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = new URL(uri).hostname; + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; + } + function loadNoProxy() { + const noProxy = getEnvironmentValue(NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); + } + return []; + } + function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return void 0; + } + } + const parsedUrl = new URL(proxyUrl); + const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; + return { + host: schema2 + parsedUrl.hostname, + port: Number.parseInt(parsedUrl.port || "80"), + username: parsedUrl.username, + password: parsedUrl.password + }; + } + function getDefaultProxySettingsInternal() { + const envProxy = loadEnvironmentProxyValue(); + return envProxy ? new URL(envProxy) : void 0; + } + function getUrlFromProxySettings(settings) { + let parsedProxyUrl; + try { + parsedProxyUrl = new URL(settings.host); + } catch (_a) { + throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); + } + parsedProxyUrl.port = String(settings.port); + if (settings.username) { + parsedProxyUrl.username = settings.username; + } + if (settings.password) { + parsedProxyUrl.password = settings.password; + } + return parsedProxyUrl; + } + function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { + if (request.agent) { + return; + } + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (request.tlsSettings) { + log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + } + const headers = request.headers.toJSON(); + if (isInsecure) { + if (!cachedAgents.httpProxyAgent) { + cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpProxyAgent; + } else { + if (!cachedAgents.httpsProxyAgent) { + cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpsProxyAgent; + } + } + function proxyPolicy(proxySettings, options) { + if (!noProxyListLoaded) { + exports2.globalNoProxyList.push(...loadNoProxy()); + } + const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); + const cachedAgents = {}; + return { + name: exports2.proxyPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { + setProxyAgentOnRequest(request, cachedAgents, defaultProxy); + } else if (request.proxySettings) { + setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js +var require_setClientRequestIdPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.setClientRequestIdPolicyName = void 0; + exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; + exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; + function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + return { + name: exports2.setClientRequestIdPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(requestIdHeaderName)) { + request.headers.set(requestIdHeaderName, request.requestId); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js +var require_tlsPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tlsPolicyName = void 0; + exports2.tlsPolicy = tlsPolicy; + exports2.tlsPolicyName = "tlsPolicy"; + function tlsPolicy(tlsSettings) { + return { + name: exports2.tlsPolicyName, + sendRequest: async (req, next) => { + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + } + }; + } + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js +var require_tracingContext = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; + exports2.knownContextKeys = { + span: Symbol.for("@azure/core-tracing span"), + namespace: Symbol.for("@azure/core-tracing namespace") + }; + function createTracingContext(options = {}) { + let context2 = new TracingContextImpl(options.parentContext); + if (options.span) { + context2 = context2.setValue(exports2.knownContextKeys.span, options.span); + } + if (options.namespace) { + context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace); + } + return context2; + } + exports2.createTracingContext = createTracingContext; + var TracingContextImpl = class _TracingContextImpl { + constructor(initialContext) { + this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); + } + setValue(key, value) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.set(key, value); + return newContext; + } + getValue(key) { + return this._contextMap.get(key); + } + deleteValue(key) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.delete(key); + return newContext; + } + }; + exports2.TracingContextImpl = TracingContextImpl; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/state.js +var require_state = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + instrumenterImplementation: void 0 + }; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js +var require_instrumenter = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; + var tracingContext_js_1 = require_tracingContext(); + var state_js_1 = require_state(); + function createDefaultTracingSpan() { + return { + end: () => { + }, + isRecording: () => false, + recordException: () => { + }, + setAttribute: () => { + }, + setStatus: () => { + } + }; + } + exports2.createDefaultTracingSpan = createDefaultTracingSpan; + function createDefaultInstrumenter() { + return { + createRequestHeaders: () => { + return {}; + }, + parseTraceparentHeader: () => { + return void 0; + }, + startSpan: (_name, spanOptions) => { + return { + span: createDefaultTracingSpan(), + tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) + }; + }, + withContext(_context, callback, ...callbackArgs) { + return callback(...callbackArgs); + } + }; + } + exports2.createDefaultInstrumenter = createDefaultInstrumenter; + function useInstrumenter(instrumenter) { + state_js_1.state.instrumenterImplementation = instrumenter; + } + exports2.useInstrumenter = useInstrumenter; + function getInstrumenter() { + if (!state_js_1.state.instrumenterImplementation) { + state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); + } + return state_js_1.state.instrumenterImplementation; + } + exports2.getInstrumenter = getInstrumenter; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js +var require_tracingClient = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = void 0; + var instrumenter_js_1 = require_instrumenter(); + var tracingContext_js_1 = require_tracingContext(); + function createTracingClient(options) { + const { namespace, packageName, packageVersion } = options; + function startSpan(name, operationOptions, spanOptions) { + var _a; + const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); + let tracingContext = startSpanResult.tracingContext; + const span = startSpanResult.span; + if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { + tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); + } + span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); + const updatedOptions = Object.assign({}, operationOptions, { + tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) + }); + return { + span, + updatedOptions + }; + } + async function withSpan(name, operationOptions, callback, spanOptions) { + const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); + try { + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); + span.setStatus({ status: "success" }); + return result; + } catch (err) { + span.setStatus({ status: "error", error: err }); + throw err; + } finally { + span.end(); + } + } + function withContext(context2, callback, ...callbackArgs) { + return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs); + } + function parseTraceparentHeader(traceparentHeader) { + return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); + } + function createRequestHeaders(tracingContext) { + return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); + } + return { + startSpan, + withSpan, + withContext, + parseTraceparentHeader, + createRequestHeaders + }; + } + exports2.createTracingClient = createTracingClient; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/index.js +var require_commonjs4 = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = exports2.useInstrumenter = void 0; + var instrumenter_js_1 = require_instrumenter(); + Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { + return instrumenter_js_1.useInstrumenter; + } }); + var tracingClient_js_1 = require_tracingClient(); + Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { + return tracingClient_js_1.createTracingClient; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js +var require_inspect = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.custom = void 0; + var node_util_1 = require("node:util"); + exports2.custom = node_util_1.inspect.custom; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js +var require_restError = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RestError = void 0; + exports2.isRestError = isRestError; + var core_util_1 = require_commonjs2(); + var inspect_js_1 = require_inspect(); + var sanitizer_js_1 = require_sanitizer(); + var errorSanitizer = new sanitizer_js_1.Sanitizer(); + var RestError = class _RestError extends Error { + constructor(message, options = {}) { + super(message); + this.name = "RestError"; + this.code = options.code; + this.statusCode = options.statusCode; + Object.defineProperty(this, "request", { value: options.request, enumerable: false }); + Object.defineProperty(this, "response", { value: options.response, enumerable: false }); + Object.setPrototypeOf(this, _RestError.prototype); + } + /** + * Logging method for util.inspect in Node + */ + [inspect_js_1.custom]() { + return `RestError: ${this.message} + ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + } + }; + exports2.RestError = RestError; + RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; + RestError.PARSE_ERROR = "PARSE_ERROR"; + function isRestError(e) { + if (e instanceof RestError) { + return true; + } + return (0, core_util_1.isError)(e) && e.name === "RestError"; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js +var require_tracingPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tracingPolicyName = void 0; + exports2.tracingPolicy = tracingPolicy; + var core_tracing_1 = require_commonjs4(); + var constants_js_1 = require_constants8(); + var userAgent_js_1 = require_userAgent(); + var log_js_1 = require_log2(); + var core_util_1 = require_commonjs2(); + var restError_js_1 = require_restError(); + var sanitizer_js_1 = require_sanitizer(); + exports2.tracingPolicyName = "tracingPolicy"; + function tracingPolicy(options = {}) { + const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + const tracingClient = tryCreateTracingClient(); + return { + name: exports2.tracingPolicyName, + async sendRequest(request, next) { + var _a; + if (!tracingClient) { + return next(request); + } + const userAgent = await userAgentPromise; + const spanAttributes = { + "http.url": sanitizer.sanitizeUrl(request.url), + "http.method": request.method, + "http.user_agent": userAgent, + requestId: request.requestId + }; + if (userAgent) { + spanAttributes["http.user_agent"] = userAgent; + } + const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; + if (!span || !tracingContext) { + return next(request); + } + try { + const response = await tracingClient.withContext(tracingContext, next, request); + tryProcessResponse(span, response); + return response; + } catch (err) { + tryProcessError(span, err); + throw err; + } + } + }; + } + function tryCreateTracingClient() { + try { + return (0, core_tracing_1.createTracingClient)({ + namespace: "", + packageName: "@azure/core-rest-pipeline", + packageVersion: constants_js_1.SDK_VERSION + }); + } catch (e) { + log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); + return void 0; + } + } + function tryCreateSpan(tracingClient, request, spanAttributes) { + try { + const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { + spanKind: "client", + spanAttributes + }); + if (!span.isRecording()) { + span.end(); + return void 0; + } + const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); + for (const [key, value] of Object.entries(headers)) { + request.headers.set(key, value); + } + return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; + } catch (e) { + log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + return void 0; + } + } + function tryProcessError(span, error2) { + try { + span.setStatus({ + status: "error", + error: (0, core_util_1.isError)(error2) ? error2 : void 0 + }); + if ((0, restError_js_1.isRestError)(error2) && error2.statusCode) { + span.setAttribute("http.status_code", error2.statusCode); + } + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + } + } + function tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + span.setStatus({ + status: "success" + }); + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + } + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js +var require_createPipelineFromOptions = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineFromOptions = createPipelineFromOptions; + var logPolicy_js_1 = require_logPolicy(); + var pipeline_js_1 = require_pipeline(); + var redirectPolicy_js_1 = require_redirectPolicy(); + var userAgentPolicy_js_1 = require_userAgentPolicy(); + var multipartPolicy_js_1 = require_multipartPolicy(); + var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); + var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); + var formDataPolicy_js_1 = require_formDataPolicy(); + var core_util_1 = require_commonjs2(); + var proxyPolicy_js_1 = require_proxyPolicy(); + var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); + var tlsPolicy_js_1 = require_tlsPolicy(); + var tracingPolicy_js_1 = require_tracingPolicy(); + function createPipelineFromOptions(options) { + var _a; + const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); + if (core_util_1.isNodeLike) { + if (options.tlsOptions) { + pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); + } + pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); + pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); + } + pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); + pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); + pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); + pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); + pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); + pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { + afterPhase: "Retry" + }); + if (core_util_1.isNodeLike) { + pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + } + pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); + return pipeline; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js +var require_nodeHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getBodyLength = getBodyLength; + exports2.createNodeHttpClient = createNodeHttpClient; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var http = tslib_1.__importStar(require("node:http")); + var https = tslib_1.__importStar(require("node:https")); + var zlib = tslib_1.__importStar(require("node:zlib")); + var node_stream_1 = require("node:stream"); + var abort_controller_1 = require_commonjs3(); + var httpHeaders_js_1 = require_httpHeaders(); + var restError_js_1 = require_restError(); + var log_js_1 = require_log2(); + var DEFAULT_TLS_SETTINGS = {}; + function isReadableStream(body) { + return body && typeof body.pipe === "function"; + } + function isStreamComplete(stream) { + return new Promise((resolve2) => { + const handler = () => { + resolve2(); + stream.removeListener("close", handler); + stream.removeListener("end", handler); + stream.removeListener("error", handler); + }; + stream.on("close", handler); + stream.on("end", handler); + stream.on("error", handler); + }); + } + function isArrayBuffer(body) { + return body && typeof body.byteLength === "number"; + } + var ReportTransform = class extends node_stream_1.Transform { + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + try { + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(); + } catch (e) { + callback(e); + } + } + constructor(progressCallback) { + super(); + this.loadedBytes = 0; + this.progressCallback = progressCallback; + } + }; + var NodeHttpClient = class { + constructor() { + this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); + } + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + var _a, _b, _c; + const abortController = new AbortController(); + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new abort_controller_1.AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController.abort(); + } + }; + request.abortSignal.addEventListener("abort", abortListener); + } + if (request.timeout > 0) { + setTimeout(() => { + abortController.abort(); + }, request.timeout); + } + const acceptEncoding = request.headers.get("Accept-Encoding"); + const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); + let body = typeof request.body === "function" ? request.body() : request.body; + if (body && !request.headers.has("Content-Length")) { + const bodyLength = getBodyLength(body); + if (bodyLength !== null) { + request.headers.set("Content-Length", bodyLength); + } + } + let responseStream; + try { + if (body && request.onUploadProgress) { + const onUploadProgress = request.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + uploadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in upload progress", e); + }); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const res = await this.makeRequest(request, abortController, body); + const headers = getResponseHeaders(res); + const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; + const response = { + status, + headers, + request + }; + if (request.method === "HEAD") { + res.resume(); + return response; + } + responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; + const onDownloadProgress = request.onDownloadProgress; + if (onDownloadProgress) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + downloadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in download progress", e); + }); + responseStream.pipe(downloadReportStream); + responseStream = downloadReportStream; + } + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) + ) { + response.readableStreamBody = responseStream; + } else { + response.bodyAsText = await streamToText(responseStream); + } + return response; + } finally { + if (request.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(responseStream)) { + downloadStreamDone = isStreamComplete(responseStream); + } + Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { + var _a2; + if (abortListener) { + (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); + } + }).catch((e) => { + log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } + makeRequest(request, abortController, body) { + var _a; + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); + const options = { + agent, + hostname: url.hostname, + path: `${url.pathname}${url.search}`, + port: url.port, + method: request.method, + headers: request.headers.toJSON({ preserveCase: true }) + }; + return new Promise((resolve2, reject) => { + const req = isInsecure ? http.request(options, resolve2) : https.request(options, resolve2); + req.once("error", (err) => { + var _a2; + reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); + }); + abortController.signal.addEventListener("abort", () => { + const abortError = new abort_controller_1.AbortError("The operation was aborted."); + req.destroy(abortError); + reject(abortError); + }); + if (body && isReadableStream(body)) { + body.pipe(req); + } else if (body) { + if (typeof body === "string" || Buffer.isBuffer(body)) { + req.end(body); + } else if (isArrayBuffer(body)) { + req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } else { + log_js_1.logger.error("Unrecognized body type", body); + reject(new restError_js_1.RestError("Unrecognized body type")); + } + } else { + req.end(); + } + }); + } + getOrCreateAgent(request, isInsecure) { + var _a; + const disableKeepAlive = request.disableKeepAlive; + if (isInsecure) { + if (disableKeepAlive) { + return http.globalAgent; + } + if (!this.cachedHttpAgent) { + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); + } + return this.cachedHttpAgent; + } else { + if (disableKeepAlive && !request.tlsSettings) { + return https.globalAgent; + } + const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; + let agent = this.cachedHttpsAgents.get(tlsSettings); + if (agent && agent.options.keepAlive === !disableKeepAlive) { + return agent; + } + log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new https.Agent(Object.assign({ + // keepAlive is true if disableKeepAlive is false. + keepAlive: !disableKeepAlive + }, tlsSettings)); + this.cachedHttpsAgents.set(tlsSettings, agent); + return agent; + } + } + }; + function getResponseHeaders(res) { + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + for (const header of Object.keys(res.headers)) { + const value = res.headers[header]; + if (Array.isArray(value)) { + if (value.length > 0) { + headers.set(header, value[0]); + } + } else if (value) { + headers.set(header, value); + } + } + return headers; + } + function getDecodedResponseStream(stream, headers) { + const contentEncoding = headers.get("Content-Encoding"); + if (contentEncoding === "gzip") { + const unzip = zlib.createGunzip(); + stream.pipe(unzip); + return unzip; + } else if (contentEncoding === "deflate") { + const inflate = zlib.createInflate(); + stream.pipe(inflate); + return inflate; + } + return stream; + } + function streamToText(stream) { + return new Promise((resolve2, reject) => { + const buffer = []; + stream.on("data", (chunk) => { + if (Buffer.isBuffer(chunk)) { + buffer.push(chunk); + } else { + buffer.push(Buffer.from(chunk)); + } + }); + stream.on("end", () => { + resolve2(Buffer.concat(buffer).toString("utf8")); + }); + stream.on("error", (e) => { + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { + reject(e); + } else { + reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { + code: restError_js_1.RestError.PARSE_ERROR + })); + } + }); + }); + } + function getBodyLength(body) { + if (!body) { + return 0; + } else if (Buffer.isBuffer(body)) { + return body.length; + } else if (isReadableStream(body)) { + return null; + } else if (isArrayBuffer(body)) { + return body.byteLength; + } else if (typeof body === "string") { + return Buffer.from(body).length; + } else { + return null; + } + } + function createNodeHttpClient() { + return new NodeHttpClient(); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js +var require_defaultHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createDefaultHttpClient = createDefaultHttpClient; + var nodeHttpClient_js_1 = require_nodeHttpClient(); + function createDefaultHttpClient() { + return (0, nodeHttpClient_js_1.createNodeHttpClient)(); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js +var require_pipelineRequest = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineRequest = createPipelineRequest; + var httpHeaders_js_1 = require_httpHeaders(); + var core_util_1 = require_commonjs2(); + var PipelineRequestImpl = class { + constructor(options) { + var _a, _b, _c, _d, _e, _f, _g; + this.url = options.url; + this.body = options.body; + this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); + this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; + this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; + this.multipartBody = options.multipartBody; + this.formData = options.formData; + this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; + this.proxySettings = options.proxySettings; + this.streamResponseStatusCodes = options.streamResponseStatusCodes; + this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; + this.abortSignal = options.abortSignal; + this.tracingOptions = options.tracingOptions; + this.onUploadProgress = options.onUploadProgress; + this.onDownloadProgress = options.onDownloadProgress; + this.requestId = options.requestId || (0, core_util_1.randomUUID)(); + this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; + this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; + } + }; + function createPipelineRequest(options) { + return new PipelineRequestImpl(options); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js +var require_exponentialRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.exponentialRetryPolicyName = void 0; + exports2.exponentialRetryPolicy = exponentialRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; + function exponentialRetryPolicy(options = {}) { + var _a; + return (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js +var require_systemErrorRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.systemErrorRetryPolicyName = void 0; + exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; + function systemErrorRetryPolicy(options = {}) { + var _a; + return { + name: exports2.systemErrorRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js +var require_throttlingRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.throttlingRetryPolicyName = void 0; + exports2.throttlingRetryPolicy = throttlingRetryPolicy; + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; + function throttlingRetryPolicy(options = {}) { + var _a; + return { + name: exports2.throttlingRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js +var require_tokenCycler = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_CYCLER_OPTIONS = void 0; + exports2.createTokenCycler = createTokenCycler; + var helpers_js_1 = require_helpers(); + exports2.DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1e3, + // Force waiting for a refresh 1s before the token expires + retryIntervalInMs: 3e3, + // Allow refresh attempts every 3s + refreshWindowInMs: 1e3 * 60 * 2 + // Start refreshing 2m before expiry + }; + async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { + async function tryGetAccessToken() { + if (Date.now() < refreshTimeout) { + try { + return await getAccessToken(); + } catch (_a) { + return null; + } + } else { + const finalToken = await getAccessToken(); + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await (0, helpers_js_1.delay)(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; + } + function createTokenCycler(credential, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + let tenantId; + const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + var _a; + if (cycler.isRefreshing) { + return false; + } + if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { + return true; + } + return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); + } + }; + function refresh(scopes, getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + refreshWorker = beginRefresh( + tryGetAccessToken, + options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() + ).then((_token) => { + refreshWorker = null; + token = _token; + tenantId = getTokenOptions.tenantId; + return token; + }).catch((reason) => { + refreshWorker = null; + token = null; + tenantId = void 0; + throw reason; + }); + } + return refreshWorker; + } + return async (scopes, tokenOptions) => { + const hasClaimChallenge = Boolean(tokenOptions.claims); + const tenantIdChanged = tenantId !== tokenOptions.tenantId; + if (hasClaimChallenge) { + token = null; + } + const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; + if (mustRefresh) { + return refresh(scopes, tokenOptions); + } + if (cycler.shouldRefresh) { + refresh(scopes, tokenOptions); + } + return token; + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js +var require_bearerTokenAuthenticationPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.bearerTokenAuthenticationPolicyName = void 0; + exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log2(); + exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; + async function defaultAuthorizeRequest(options) { + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + const accessToken = await getAccessToken(scopes, getTokenOptions); + if (accessToken) { + options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + } + } + function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; + } + return; + } + function bearerTokenAuthenticationPolicy(options) { + var _a; + const { credential, scopes, challengeCallbacks } = options; + const logger = options.logger || log_js_1.logger; + const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); + const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( + credential + /* , options */ + ) : () => Promise.resolve(null); + return { + name: exports2.bearerTokenAuthenticationPolicyName, + /** + * If there's no challenge parameter: + * - It will try to retrieve the token using the cache, or the credential's getToken. + * - Then it will try the next policy with or without the retrieved token. + * + * It uses the challenge parameters to: + * - Skip a first attempt to get the token from the credential if there's no cached token, + * since it expects the token to be retrievable only after the challenge. + * - Prepare the outgoing request if the `prepareRequest` method has been provided. + * - Send an initial request to receive the challenge if it fails. + * - Process a challenge if the response contains it. + * - Retrieve a token with the challenge information, then re-send the request. + */ + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + await callbacks.authorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + }); + let response; + let error2; + try { + response = await next(request); + } catch (err) { + error2 = err; + response = err.response; + } + if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { + const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + response, + getAccessToken, + logger + }); + if (shouldSendRequest) { + return next(request); + } + } + if (error2) { + throw error2; + } else { + return response; + } + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js +var require_ndJsonPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ndJsonPolicyName = void 0; + exports2.ndJsonPolicy = ndJsonPolicy; + exports2.ndJsonPolicyName = "ndJsonPolicy"; + function ndJsonPolicy() { + return { + name: exports2.ndJsonPolicyName, + async sendRequest(request, next) { + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js +var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; + exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log2(); + exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; + var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; + async function sendAuthorizeRequest(options) { + var _a, _b; + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; + } + function auxiliaryAuthenticationHeaderPolicy(options) { + const { credentials, scopes } = options; + const logger = options.logger || log_js_1.logger; + const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); + return { + name: exports2.auxiliaryAuthenticationHeaderPolicyName, + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); + } + if (!credentials || credentials.length === 0) { + logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); + return next(request); + } + const tokenPromises = []; + for (const credential of credentials) { + let getAccessToken = tokenCyclerMap.get(credential); + if (!getAccessToken) { + getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); + tokenCyclerMap.set(credential, getAccessToken); + } + tokenPromises.push(sendAuthorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + })); + } + const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); + if (auxiliaryTokens.length === 0) { + logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); + return next(request); + } + request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js +var require_commonjs5 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; + var pipeline_js_1 = require_pipeline(); + Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { + return pipeline_js_1.createEmptyPipeline; + } }); + var createPipelineFromOptions_js_1 = require_createPipelineFromOptions(); + Object.defineProperty(exports2, "createPipelineFromOptions", { enumerable: true, get: function() { + return createPipelineFromOptions_js_1.createPipelineFromOptions; + } }); + var defaultHttpClient_js_1 = require_defaultHttpClient(); + Object.defineProperty(exports2, "createDefaultHttpClient", { enumerable: true, get: function() { + return defaultHttpClient_js_1.createDefaultHttpClient; + } }); + var httpHeaders_js_1 = require_httpHeaders(); + Object.defineProperty(exports2, "createHttpHeaders", { enumerable: true, get: function() { + return httpHeaders_js_1.createHttpHeaders; + } }); + var pipelineRequest_js_1 = require_pipelineRequest(); + Object.defineProperty(exports2, "createPipelineRequest", { enumerable: true, get: function() { + return pipelineRequest_js_1.createPipelineRequest; + } }); + var restError_js_1 = require_restError(); + Object.defineProperty(exports2, "RestError", { enumerable: true, get: function() { + return restError_js_1.RestError; + } }); + Object.defineProperty(exports2, "isRestError", { enumerable: true, get: function() { + return restError_js_1.isRestError; + } }); + var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); + Object.defineProperty(exports2, "decompressResponsePolicy", { enumerable: true, get: function() { + return decompressResponsePolicy_js_1.decompressResponsePolicy; + } }); + Object.defineProperty(exports2, "decompressResponsePolicyName", { enumerable: true, get: function() { + return decompressResponsePolicy_js_1.decompressResponsePolicyName; + } }); + var exponentialRetryPolicy_js_1 = require_exponentialRetryPolicy(); + Object.defineProperty(exports2, "exponentialRetryPolicy", { enumerable: true, get: function() { + return exponentialRetryPolicy_js_1.exponentialRetryPolicy; + } }); + Object.defineProperty(exports2, "exponentialRetryPolicyName", { enumerable: true, get: function() { + return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; + } }); + var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); + Object.defineProperty(exports2, "setClientRequestIdPolicy", { enumerable: true, get: function() { + return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; + } }); + Object.defineProperty(exports2, "setClientRequestIdPolicyName", { enumerable: true, get: function() { + return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; + } }); + var logPolicy_js_1 = require_logPolicy(); + Object.defineProperty(exports2, "logPolicy", { enumerable: true, get: function() { + return logPolicy_js_1.logPolicy; + } }); + Object.defineProperty(exports2, "logPolicyName", { enumerable: true, get: function() { + return logPolicy_js_1.logPolicyName; + } }); + var multipartPolicy_js_1 = require_multipartPolicy(); + Object.defineProperty(exports2, "multipartPolicy", { enumerable: true, get: function() { + return multipartPolicy_js_1.multipartPolicy; + } }); + Object.defineProperty(exports2, "multipartPolicyName", { enumerable: true, get: function() { + return multipartPolicy_js_1.multipartPolicyName; + } }); + var proxyPolicy_js_1 = require_proxyPolicy(); + Object.defineProperty(exports2, "proxyPolicy", { enumerable: true, get: function() { + return proxyPolicy_js_1.proxyPolicy; + } }); + Object.defineProperty(exports2, "proxyPolicyName", { enumerable: true, get: function() { + return proxyPolicy_js_1.proxyPolicyName; + } }); + Object.defineProperty(exports2, "getDefaultProxySettings", { enumerable: true, get: function() { + return proxyPolicy_js_1.getDefaultProxySettings; + } }); + var redirectPolicy_js_1 = require_redirectPolicy(); + Object.defineProperty(exports2, "redirectPolicy", { enumerable: true, get: function() { + return redirectPolicy_js_1.redirectPolicy; + } }); + Object.defineProperty(exports2, "redirectPolicyName", { enumerable: true, get: function() { + return redirectPolicy_js_1.redirectPolicyName; + } }); + var systemErrorRetryPolicy_js_1 = require_systemErrorRetryPolicy(); + Object.defineProperty(exports2, "systemErrorRetryPolicy", { enumerable: true, get: function() { + return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; + } }); + Object.defineProperty(exports2, "systemErrorRetryPolicyName", { enumerable: true, get: function() { + return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; + } }); + var throttlingRetryPolicy_js_1 = require_throttlingRetryPolicy(); + Object.defineProperty(exports2, "throttlingRetryPolicy", { enumerable: true, get: function() { + return throttlingRetryPolicy_js_1.throttlingRetryPolicy; + } }); + Object.defineProperty(exports2, "throttlingRetryPolicyName", { enumerable: true, get: function() { + return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; + } }); + var retryPolicy_js_1 = require_retryPolicy(); + Object.defineProperty(exports2, "retryPolicy", { enumerable: true, get: function() { + return retryPolicy_js_1.retryPolicy; + } }); + var tracingPolicy_js_1 = require_tracingPolicy(); + Object.defineProperty(exports2, "tracingPolicy", { enumerable: true, get: function() { + return tracingPolicy_js_1.tracingPolicy; + } }); + Object.defineProperty(exports2, "tracingPolicyName", { enumerable: true, get: function() { + return tracingPolicy_js_1.tracingPolicyName; + } }); + var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); + Object.defineProperty(exports2, "defaultRetryPolicy", { enumerable: true, get: function() { + return defaultRetryPolicy_js_1.defaultRetryPolicy; + } }); + var userAgentPolicy_js_1 = require_userAgentPolicy(); + Object.defineProperty(exports2, "userAgentPolicy", { enumerable: true, get: function() { + return userAgentPolicy_js_1.userAgentPolicy; + } }); + Object.defineProperty(exports2, "userAgentPolicyName", { enumerable: true, get: function() { + return userAgentPolicy_js_1.userAgentPolicyName; + } }); + var tlsPolicy_js_1 = require_tlsPolicy(); + Object.defineProperty(exports2, "tlsPolicy", { enumerable: true, get: function() { + return tlsPolicy_js_1.tlsPolicy; + } }); + Object.defineProperty(exports2, "tlsPolicyName", { enumerable: true, get: function() { + return tlsPolicy_js_1.tlsPolicyName; + } }); + var formDataPolicy_js_1 = require_formDataPolicy(); + Object.defineProperty(exports2, "formDataPolicy", { enumerable: true, get: function() { + return formDataPolicy_js_1.formDataPolicy; + } }); + Object.defineProperty(exports2, "formDataPolicyName", { enumerable: true, get: function() { + return formDataPolicy_js_1.formDataPolicyName; + } }); + var bearerTokenAuthenticationPolicy_js_1 = require_bearerTokenAuthenticationPolicy(); + Object.defineProperty(exports2, "bearerTokenAuthenticationPolicy", { enumerable: true, get: function() { + return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; + } }); + Object.defineProperty(exports2, "bearerTokenAuthenticationPolicyName", { enumerable: true, get: function() { + return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; + } }); + var ndJsonPolicy_js_1 = require_ndJsonPolicy(); + Object.defineProperty(exports2, "ndJsonPolicy", { enumerable: true, get: function() { + return ndJsonPolicy_js_1.ndJsonPolicy; + } }); + Object.defineProperty(exports2, "ndJsonPolicyName", { enumerable: true, get: function() { + return ndJsonPolicy_js_1.ndJsonPolicyName; + } }); + var auxiliaryAuthenticationHeaderPolicy_js_1 = require_auxiliaryAuthenticationHeaderPolicy(); + Object.defineProperty(exports2, "auxiliaryAuthenticationHeaderPolicy", { enumerable: true, get: function() { + return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; + } }); + Object.defineProperty(exports2, "auxiliaryAuthenticationHeaderPolicyName", { enumerable: true, get: function() { + return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; + } }); + var file_js_1 = require_file2(); + Object.defineProperty(exports2, "createFile", { enumerable: true, get: function() { + return file_js_1.createFile; + } }); + Object.defineProperty(exports2, "createFileFromStream", { enumerable: true, get: function() { + return file_js_1.createFileFromStream; + } }); + } +}); + +// node_modules/@azure/storage-blob/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports2 = {}; +__export(tslib_es6_exports2, { + __addDisposableResource: () => __addDisposableResource2, + __assign: () => __assign2, + __asyncDelegator: () => __asyncDelegator2, + __asyncGenerator: () => __asyncGenerator2, + __asyncValues: () => __asyncValues2, + __await: () => __await2, + __awaiter: () => __awaiter2, + __classPrivateFieldGet: () => __classPrivateFieldGet2, + __classPrivateFieldIn: () => __classPrivateFieldIn2, + __classPrivateFieldSet: () => __classPrivateFieldSet2, + __createBinding: () => __createBinding2, + __decorate: () => __decorate2, + __disposeResources: () => __disposeResources2, + __esDecorate: () => __esDecorate2, + __exportStar: () => __exportStar2, + __extends: () => __extends2, + __generator: () => __generator2, + __importDefault: () => __importDefault2, + __importStar: () => __importStar2, + __makeTemplateObject: () => __makeTemplateObject2, + __metadata: () => __metadata2, + __param: () => __param2, + __propKey: () => __propKey2, + __read: () => __read2, + __rest: () => __rest2, + __runInitializers: () => __runInitializers2, + __setFunctionName: () => __setFunctionName2, + __spread: () => __spread2, + __spreadArray: () => __spreadArray2, + __spreadArrays: () => __spreadArrays2, + __values: () => __values3, + default: () => tslib_es6_default2 +}); +function __extends2(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics2(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest2(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; +} +function __decorate2(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; +} +function __param2(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate2(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 context2 = {}; + for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; + context2.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], context2); + 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.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers2(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; +} +function __propKey2(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName2(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 }); +} +function __metadata2(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter2(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator2(thisArg, body) { + var _ = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["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 (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]) { + 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 }; + } +} +function __exportStar2(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding2(o, m, p); +} +function __values3(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."); +} +function __read2(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 (error2) { + e = { error: error2 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread2() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read2(arguments[i])); + return ar; +} +function __spreadArrays2() { + 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; +} +function __spreadArray2(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)); +} +function __await2(v) { + return this instanceof __await2 ? (this.v = v, this) : new __await2(v); +} +function __asyncGenerator2(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await2 ? 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]); + } +} +function __asyncDelegator2(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: __await2(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues2(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 __values3 === "function" ? __values3(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(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject2(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar2(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)) __createBinding2(result, mod, k); + } + __setModuleDefault2(result, mod); + return result; +} +function __importDefault2(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet2(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); +} +function __classPrivateFieldSet2(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; +} +function __classPrivateFieldIn2(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); +} +function __addDisposableResource2(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources2(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics2, __assign2, __createBinding2, __setModuleDefault2, _SuppressedError2, tslib_es6_default2; +var init_tslib_es62 = __esm({ + "node_modules/@azure/storage-blob/node_modules/tslib/tslib.es6.mjs"() { + extendStatics2 = function(d, b) { + extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics2(d, b); + }; + __assign2 = function() { + __assign2 = Object.assign || function __assign4(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; + }; + return __assign2.apply(this, arguments); + }; + __createBinding2 = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault2 = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + _SuppressedError2 = typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error2, e.suppressed = suppressed, e; + }; + tslib_es6_default2 = { + __extends: __extends2, + __assign: __assign2, + __rest: __rest2, + __decorate: __decorate2, + __param: __param2, + __metadata: __metadata2, + __awaiter: __awaiter2, + __generator: __generator2, + __createBinding: __createBinding2, + __exportStar: __exportStar2, + __values: __values3, + __read: __read2, + __spread: __spread2, + __spreadArrays: __spreadArrays2, + __spreadArray: __spreadArray2, + __await: __await2, + __asyncGenerator: __asyncGenerator2, + __asyncDelegator: __asyncDelegator2, + __asyncValues: __asyncValues2, + __makeTemplateObject: __makeTemplateObject2, + __importStar: __importStar2, + __importDefault: __importDefault2, + __classPrivateFieldGet: __classPrivateFieldGet2, + __classPrivateFieldSet: __classPrivateFieldSet2, + __classPrivateFieldIn: __classPrivateFieldIn2, + __addDisposableResource: __addDisposableResource2, + __disposeResources: __disposeResources2 + }; + } +}); + +// node_modules/@azure/core-auth/dist/commonjs/azureKeyCredential.js +var require_azureKeyCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/azureKeyCredential.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AzureKeyCredential = void 0; + var AzureKeyCredential = class { + /** + * The value of the key to be used in authentication + */ + get key() { + return this._key; + } + /** + * Create an instance of an AzureKeyCredential for use + * with a service client. + * + * @param key - The initial value of the key to use in authentication + */ + constructor(key) { + if (!key) { + throw new Error("key must be a non-empty string"); + } + this._key = key; + } + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey - The new key value to be used + */ + update(newKey) { + this._key = newKey; + } + }; + exports2.AzureKeyCredential = AzureKeyCredential; + } +}); + +// node_modules/@azure/core-auth/dist/commonjs/keyCredential.js +var require_keyCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/keyCredential.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isKeyCredential = isKeyCredential; + var core_util_1 = require_commonjs2(); + function isKeyCredential(credential) { + return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string"; + } + } +}); + +// node_modules/@azure/core-auth/dist/commonjs/azureNamedKeyCredential.js +var require_azureNamedKeyCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/azureNamedKeyCredential.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AzureNamedKeyCredential = void 0; + exports2.isNamedKeyCredential = isNamedKeyCredential; + var core_util_1 = require_commonjs2(); + var AzureNamedKeyCredential = class { + /** + * The value of the key to be used in authentication. + */ + get key() { + return this._key; + } + /** + * The value of the name to be used in authentication. + */ + get name() { + return this._name; + } + /** + * Create an instance of an AzureNamedKeyCredential for use + * with a service client. + * + * @param name - The initial value of the name to use in authentication. + * @param key - The initial value of the key to use in authentication. + */ + constructor(name, key) { + if (!name || !key) { + throw new TypeError("name and key must be non-empty strings"); + } + this._name = name; + this._key = key; + } + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newName - The new name value to be used. + * @param newKey - The new key value to be used. + */ + update(newName, newKey) { + if (!newName || !newKey) { + throw new TypeError("newName and newKey must be non-empty strings"); + } + this._name = newName; + this._key = newKey; + } + }; + exports2.AzureNamedKeyCredential = AzureNamedKeyCredential; + function isNamedKeyCredential(credential) { + return (0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) && typeof credential.key === "string" && typeof credential.name === "string"; + } + } +}); + +// node_modules/@azure/core-auth/dist/commonjs/azureSASCredential.js +var require_azureSASCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/azureSASCredential.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AzureSASCredential = void 0; + exports2.isSASCredential = isSASCredential; + var core_util_1 = require_commonjs2(); + var AzureSASCredential = class { + /** + * The value of the shared access signature to be used in authentication + */ + get signature() { + return this._signature; + } + /** + * Create an instance of an AzureSASCredential for use + * with a service client. + * + * @param signature - The initial value of the shared access signature to use in authentication + */ + constructor(signature) { + if (!signature) { + throw new Error("shared access signature must be a non-empty string"); + } + this._signature = signature; + } + /** + * Change the value of the signature. + * + * Updates will take effect upon the next request after + * updating the signature value. + * + * @param newSignature - The new shared access signature value to be used + */ + update(newSignature) { + if (!newSignature) { + throw new Error("shared access signature must be a non-empty string"); + } + this._signature = newSignature; + } + }; + exports2.AzureSASCredential = AzureSASCredential; + function isSASCredential(credential) { + return (0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string"; + } + } +}); + +// node_modules/@azure/core-auth/dist/commonjs/tokenCredential.js +var require_tokenCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/tokenCredential.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isTokenCredential = isTokenCredential; + function isTokenCredential(credential) { + const castCredential = credential; + return castCredential && typeof castCredential.getToken === "function" && (castCredential.signRequest === void 0 || castCredential.getToken.length > 0); + } + } +}); + +// node_modules/@azure/core-auth/dist/commonjs/index.js +var require_commonjs6 = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isTokenCredential = exports2.isSASCredential = exports2.AzureSASCredential = exports2.isNamedKeyCredential = exports2.AzureNamedKeyCredential = exports2.isKeyCredential = exports2.AzureKeyCredential = void 0; + var azureKeyCredential_js_1 = require_azureKeyCredential(); + Object.defineProperty(exports2, "AzureKeyCredential", { enumerable: true, get: function() { + return azureKeyCredential_js_1.AzureKeyCredential; + } }); + var keyCredential_js_1 = require_keyCredential(); + Object.defineProperty(exports2, "isKeyCredential", { enumerable: true, get: function() { + return keyCredential_js_1.isKeyCredential; + } }); + var azureNamedKeyCredential_js_1 = require_azureNamedKeyCredential(); + Object.defineProperty(exports2, "AzureNamedKeyCredential", { enumerable: true, get: function() { + return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; + } }); + Object.defineProperty(exports2, "isNamedKeyCredential", { enumerable: true, get: function() { + return azureNamedKeyCredential_js_1.isNamedKeyCredential; + } }); + var azureSASCredential_js_1 = require_azureSASCredential(); + Object.defineProperty(exports2, "AzureSASCredential", { enumerable: true, get: function() { + return azureSASCredential_js_1.AzureSASCredential; + } }); + Object.defineProperty(exports2, "isSASCredential", { enumerable: true, get: function() { + return azureSASCredential_js_1.isSASCredential; + } }); + var tokenCredential_js_1 = require_tokenCredential(); + Object.defineProperty(exports2, "isTokenCredential", { enumerable: true, get: function() { + return tokenCredential_js_1.isTokenCredential; + } }); + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js +var require_disableKeepAlivePolicy = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.pipelineContainsDisableKeepAlivePolicy = exports2.createDisableKeepAlivePolicy = exports2.disableKeepAlivePolicyName = void 0; + exports2.disableKeepAlivePolicyName = "DisableKeepAlivePolicy"; + function createDisableKeepAlivePolicy() { + return { + name: exports2.disableKeepAlivePolicyName, + async sendRequest(request, next) { + request.disableKeepAlive = true; + return next(request); + } + }; + } + exports2.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy; + function pipelineContainsDisableKeepAlivePolicy(pipeline) { + return pipeline.getOrderedPolicies().some((policy) => policy.name === exports2.disableKeepAlivePolicyName); + } + exports2.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy; + } +}); + +// node_modules/@azure/core-client/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports3 = {}; +__export(tslib_es6_exports3, { + __addDisposableResource: () => __addDisposableResource3, + __assign: () => __assign3, + __asyncDelegator: () => __asyncDelegator3, + __asyncGenerator: () => __asyncGenerator3, + __asyncValues: () => __asyncValues3, + __await: () => __await3, + __awaiter: () => __awaiter3, + __classPrivateFieldGet: () => __classPrivateFieldGet3, + __classPrivateFieldIn: () => __classPrivateFieldIn3, + __classPrivateFieldSet: () => __classPrivateFieldSet3, + __createBinding: () => __createBinding3, + __decorate: () => __decorate3, + __disposeResources: () => __disposeResources3, + __esDecorate: () => __esDecorate3, + __exportStar: () => __exportStar3, + __extends: () => __extends3, + __generator: () => __generator3, + __importDefault: () => __importDefault3, + __importStar: () => __importStar3, + __makeTemplateObject: () => __makeTemplateObject3, + __metadata: () => __metadata3, + __param: () => __param3, + __propKey: () => __propKey3, + __read: () => __read3, + __rest: () => __rest3, + __runInitializers: () => __runInitializers3, + __setFunctionName: () => __setFunctionName3, + __spread: () => __spread3, + __spreadArray: () => __spreadArray3, + __spreadArrays: () => __spreadArrays3, + __values: () => __values4, + default: () => tslib_es6_default3 +}); +function __extends3(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics3(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest3(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; +} +function __decorate3(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; +} +function __param3(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate3(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 context2 = {}; + for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; + context2.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], context2); + 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.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers3(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; +} +function __propKey3(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName3(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 }); +} +function __metadata3(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter3(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator3(thisArg, body) { + var _ = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["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 (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]) { + 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 }; + } +} +function __exportStar3(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding3(o, m, p); +} +function __values4(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."); +} +function __read3(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 (error2) { + e = { error: error2 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread3() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read3(arguments[i])); + return ar; +} +function __spreadArrays3() { + 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; +} +function __spreadArray3(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)); +} +function __await3(v) { + return this instanceof __await3 ? (this.v = v, this) : new __await3(v); +} +function __asyncGenerator3(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await3 ? 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]); + } +} +function __asyncDelegator3(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: __await3(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues3(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 __values4 === "function" ? __values4(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(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject3(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar3(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)) __createBinding3(result, mod, k); + } + __setModuleDefault3(result, mod); + return result; +} +function __importDefault3(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet3(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); +} +function __classPrivateFieldSet3(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; +} +function __classPrivateFieldIn3(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); +} +function __addDisposableResource3(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources3(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError3(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics3, __assign3, __createBinding3, __setModuleDefault3, _SuppressedError3, tslib_es6_default3; +var init_tslib_es63 = __esm({ + "node_modules/@azure/core-client/node_modules/tslib/tslib.es6.mjs"() { + extendStatics3 = function(d, b) { + extendStatics3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics3(d, b); + }; + __assign3 = function() { + __assign3 = Object.assign || function __assign4(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; + }; + return __assign3.apply(this, arguments); + }; + __createBinding3 = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault3 = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + _SuppressedError3 = typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error2, e.suppressed = suppressed, e; + }; + tslib_es6_default3 = { + __extends: __extends3, + __assign: __assign3, + __rest: __rest3, + __decorate: __decorate3, + __param: __param3, + __metadata: __metadata3, + __awaiter: __awaiter3, + __generator: __generator3, + __createBinding: __createBinding3, + __exportStar: __exportStar3, + __values: __values4, + __read: __read3, + __spread: __spread3, + __spreadArrays: __spreadArrays3, + __spreadArray: __spreadArray3, + __await: __await3, + __asyncGenerator: __asyncGenerator3, + __asyncDelegator: __asyncDelegator3, + __asyncValues: __asyncValues3, + __makeTemplateObject: __makeTemplateObject3, + __importStar: __importStar3, + __importDefault: __importDefault3, + __classPrivateFieldGet: __classPrivateFieldGet3, + __classPrivateFieldSet: __classPrivateFieldSet3, + __classPrivateFieldIn: __classPrivateFieldIn3, + __addDisposableResource: __addDisposableResource3, + __disposeResources: __disposeResources3 + }; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/base64.js +var require_base64 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/base64.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decodeStringToString = exports2.decodeString = exports2.encodeByteArray = exports2.encodeString = void 0; + function encodeString(value) { + return Buffer.from(value).toString("base64"); + } + exports2.encodeString = encodeString; + function encodeByteArray(value) { + const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); + return bufferValue.toString("base64"); + } + exports2.encodeByteArray = encodeByteArray; + function decodeString(value) { + return Buffer.from(value, "base64"); + } + exports2.decodeString = decodeString; + function decodeStringToString(value) { + return Buffer.from(value, "base64").toString(); + } + exports2.decodeStringToString = decodeStringToString; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/interfaces.js +var require_interfaces = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/interfaces.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.XML_CHARKEY = exports2.XML_ATTRKEY = void 0; + exports2.XML_ATTRKEY = "$"; + exports2.XML_CHARKEY = "_"; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/utils.js +var require_utils5 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/utils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.flattenResponse = exports2.isValidUuid = exports2.isDuration = exports2.isPrimitiveBody = void 0; + function isPrimitiveBody(value, mapperTypeName) { + return mapperTypeName !== "Composite" && mapperTypeName !== "Dictionary" && (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !== null || value === void 0 || value === null); + } + exports2.isPrimitiveBody = isPrimitiveBody; + var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + function isDuration(value) { + return validateISODuration.test(value); + } + exports2.isDuration = isDuration; + var validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; + function isValidUuid(uuid) { + return validUuidRegex.test(uuid); + } + exports2.isValidUuid = isValidUuid; + function handleNullableResponseAndWrappableBody(responseObject) { + const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body); + if (responseObject.hasNullableType && Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) { + return responseObject.shouldWrapBody ? { body: null } : null; + } else { + return responseObject.shouldWrapBody ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody; + } + } + function flattenResponse(fullResponse, responseSpec) { + var _a, _b; + const parsedHeaders = fullResponse.parsedHeaders; + if (fullResponse.request.method === "HEAD") { + return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody }); + } + const bodyMapper = responseSpec && responseSpec.bodyMapper; + const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable); + const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name; + if (expectedBodyTypeName === "Stream") { + return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody }); + } + const modelProperties = expectedBodyTypeName === "Composite" && bodyMapper.type.modelProperties || {}; + const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); + if (expectedBodyTypeName === "Sequence" || isPageableResponse) { + const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : []; + for (const key of Object.keys(modelProperties)) { + if (modelProperties[key].serializedName) { + arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key]; + } + } + if (parsedHeaders) { + for (const key of Object.keys(parsedHeaders)) { + arrayResponse[key] = parsedHeaders[key]; + } + } + return isNullable && !fullResponse.parsedBody && !parsedHeaders && Object.getOwnPropertyNames(modelProperties).length === 0 ? null : arrayResponse; + } + return handleNullableResponseAndWrappableBody({ + body: fullResponse.parsedBody, + headers: parsedHeaders, + hasNullableType: isNullable, + shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName) + }); + } + exports2.flattenResponse = flattenResponse; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/serializer.js +var require_serializer = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/serializer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MapperTypeNames = exports2.createSerializer = void 0; + var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3)); + var base64 = tslib_1.__importStar(require_base64()); + var interfaces_js_1 = require_interfaces(); + var utils_js_1 = require_utils5(); + var SerializerImpl = class { + constructor(modelMappers = {}, isXML = false) { + this.modelMappers = modelMappers; + this.isXML = isXML; + } + /** + * @deprecated Removing the constraints validation on client side. + */ + validateConstraints(mapper, value, objectName) { + const failValidation = (constraintName, constraintValue) => { + throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); + }; + if (mapper.constraints && value !== void 0 && value !== null) { + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems } = mapper.constraints; + if (ExclusiveMaximum !== void 0 && value >= ExclusiveMaximum) { + failValidation("ExclusiveMaximum", ExclusiveMaximum); + } + if (ExclusiveMinimum !== void 0 && value <= ExclusiveMinimum) { + failValidation("ExclusiveMinimum", ExclusiveMinimum); + } + if (InclusiveMaximum !== void 0 && value > InclusiveMaximum) { + failValidation("InclusiveMaximum", InclusiveMaximum); + } + if (InclusiveMinimum !== void 0 && value < InclusiveMinimum) { + failValidation("InclusiveMinimum", InclusiveMinimum); + } + if (MaxItems !== void 0 && value.length > MaxItems) { + failValidation("MaxItems", MaxItems); + } + if (MaxLength !== void 0 && value.length > MaxLength) { + failValidation("MaxLength", MaxLength); + } + if (MinItems !== void 0 && value.length < MinItems) { + failValidation("MinItems", MinItems); + } + if (MinLength !== void 0 && value.length < MinLength) { + failValidation("MinLength", MinLength); + } + if (MultipleOf !== void 0 && value % MultipleOf !== 0) { + failValidation("MultipleOf", MultipleOf); + } + if (Pattern) { + const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; + if (typeof value !== "string" || value.match(pattern) === null) { + failValidation("Pattern", Pattern); + } + } + if (UniqueItems && value.some((item, i, ar) => ar.indexOf(item) !== i)) { + failValidation("UniqueItems", UniqueItems); + } + } + } + /** + * Serialize the given object based on its metadata defined in the mapper + * + * @param mapper - The mapper which defines the metadata of the serializable object + * + * @param object - A valid Javascript object to be serialized + * + * @param objectName - Name of the serialized object + * + * @param options - additional options to serialization + * + * @returns A valid serialized Javascript object + */ + serialize(mapper, object, objectName, options = { xml: {} }) { + var _a, _b, _c; + const updatedOptions = { + xml: { + rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY + } + }; + let payload = {}; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; + } + if (mapperType.match(/^Sequence$/i) !== null) { + payload = []; + } + if (mapper.isConstant) { + object = mapper.defaultValue; + } + const { required, nullable } = mapper; + if (required && nullable && object === void 0) { + throw new Error(`${objectName} cannot be undefined.`); + } + if (required && !nullable && (object === void 0 || object === null)) { + throw new Error(`${objectName} cannot be null or undefined.`); + } + if (!required && nullable === false && object === null) { + throw new Error(`${objectName} cannot be null.`); + } + if (object === void 0 || object === null) { + payload = object; + } else { + if (mapperType.match(/^any$/i) !== null) { + payload = object; + } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { + payload = serializeBasicTypes(mapperType, objectName, object); + } else if (mapperType.match(/^Enum$/i) !== null) { + const enumMapper = mapper; + payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); + } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { + payload = serializeDateTypes(mapperType, object, objectName); + } else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = serializeByteArrayType(objectName, object); + } else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = serializeBase64UrlType(objectName, object); + } else if (mapperType.match(/^Sequence$/i) !== null) { + payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } else if (mapperType.match(/^Composite$/i) !== null) { + payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } + } + return payload; + } + /** + * Deserialize the given object based on its metadata defined in the mapper + * + * @param mapper - The mapper which defines the metadata of the serializable object + * + * @param responseBody - A valid Javascript entity to be deserialized + * + * @param objectName - Name of the deserialized object + * + * @param options - Controls behavior of XML parser and builder. + * + * @returns A valid deserialized Javascript object + */ + deserialize(mapper, responseBody, objectName, options = { xml: {} }) { + var _a, _b, _c, _d; + const updatedOptions = { + xml: { + rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY + }, + ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false + }; + if (responseBody === void 0 || responseBody === null) { + if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { + responseBody = []; + } + if (mapper.defaultValue !== void 0) { + responseBody = mapper.defaultValue; + } + return responseBody; + } + let payload; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; + } + if (mapperType.match(/^Composite$/i) !== null) { + payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); + } else { + if (this.isXML) { + const xmlCharKey = updatedOptions.xml.xmlCharKey; + if (responseBody[interfaces_js_1.XML_ATTRKEY] !== void 0 && responseBody[xmlCharKey] !== void 0) { + responseBody = responseBody[xmlCharKey]; + } + } + if (mapperType.match(/^Number$/i) !== null) { + payload = parseFloat(responseBody); + if (isNaN(payload)) { + payload = responseBody; + } + } else if (mapperType.match(/^Boolean$/i) !== null) { + if (responseBody === "true") { + payload = true; + } else if (responseBody === "false") { + payload = false; + } else { + payload = responseBody; + } + } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { + payload = responseBody; + } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { + payload = new Date(responseBody); + } else if (mapperType.match(/^UnixTime$/i) !== null) { + payload = unixTimeToDate(responseBody); + } else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = base64.decodeString(responseBody); + } else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = base64UrlToByteArray(responseBody); + } else if (mapperType.match(/^Sequence$/i) !== null) { + payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); + } else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); + } + } + if (mapper.isConstant) { + payload = mapper.defaultValue; + } + return payload; + } + }; + function createSerializer(modelMappers = {}, isXML = false) { + return new SerializerImpl(modelMappers, isXML); + } + exports2.createSerializer = createSerializer; + function trimEnd(str2, ch) { + let len = str2.length; + while (len - 1 >= 0 && str2[len - 1] === ch) { + --len; + } + return str2.substr(0, len); + } + function bufferToBase64Url(buffer) { + if (!buffer) { + return void 0; + } + if (!(buffer instanceof Uint8Array)) { + throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); + } + const str2 = base64.encodeByteArray(buffer); + return trimEnd(str2, "=").replace(/\+/g, "-").replace(/\//g, "_"); + } + function base64UrlToByteArray(str2) { + if (!str2) { + return void 0; + } + if (str2 && typeof str2.valueOf() !== "string") { + throw new Error("Please provide an input of type string for converting to Uint8Array"); + } + str2 = str2.replace(/-/g, "+").replace(/_/g, "/"); + return base64.decodeString(str2); + } + function splitSerializeName(prop) { + const classes = []; + let partialclass = ""; + if (prop) { + const subwords = prop.split("."); + for (const item of subwords) { + if (item.charAt(item.length - 1) === "\\") { + partialclass += item.substr(0, item.length - 1) + "."; + } else { + partialclass += item; + classes.push(partialclass); + partialclass = ""; + } + } + } + return classes; + } + function dateToUnixTime(d) { + if (!d) { + return void 0; + } + if (typeof d.valueOf() === "string") { + d = new Date(d); + } + return Math.floor(d.getTime() / 1e3); + } + function unixTimeToDate(n) { + if (!n) { + return void 0; + } + return new Date(n * 1e3); + } + function serializeBasicTypes(typeName, objectName, value) { + if (value !== null && value !== void 0) { + if (typeName.match(/^Number$/i) !== null) { + if (typeof value !== "number") { + throw new Error(`${objectName} with value ${value} must be of type number.`); + } + } else if (typeName.match(/^String$/i) !== null) { + if (typeof value.valueOf() !== "string") { + throw new Error(`${objectName} with value "${value}" must be of type string.`); + } + } else if (typeName.match(/^Uuid$/i) !== null) { + if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) { + throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); + } + } else if (typeName.match(/^Boolean$/i) !== null) { + if (typeof value !== "boolean") { + throw new Error(`${objectName} with value ${value} must be of type boolean.`); + } + } else if (typeName.match(/^Stream$/i) !== null) { + const objectType = typeof value; + if (objectType !== "string" && typeof value.pipe !== "function" && // NodeJS.ReadableStream + typeof value.tee !== "function" && // browser ReadableStream + !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && // File objects count as a type of Blob, so we want to use instanceof explicitly + !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) && objectType !== "function") { + throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`); + } + } + } + return value; + } + function serializeEnumType(objectName, allowedValues, value) { + if (!allowedValues) { + throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); + } + const isPresent = allowedValues.some((item) => { + if (typeof item.valueOf() === "string") { + return item.toLowerCase() === value.toLowerCase(); + } + return item === value; + }); + if (!isPresent) { + throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); + } + return value; + } + function serializeByteArrayType(objectName, value) { + if (value !== void 0 && value !== null) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); + } + value = base64.encodeByteArray(value); + } + return value; + } + function serializeBase64UrlType(objectName, value) { + if (value !== void 0 && value !== null) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); + } + value = bufferToBase64Url(value); + } + return value; + } + function serializeDateTypes(typeName, value, objectName) { + if (value !== void 0 && value !== null) { + if (typeName.match(/^Date$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = value instanceof Date ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10); + } else if (typeName.match(/^DateTime$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); + } + value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); + } else if (typeName.match(/^UnixTime$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format for it to be serialized in UnixTime/Epoch format.`); + } + value = dateToUnixTime(value); + } else if (typeName.match(/^TimeSpan$/i) !== null) { + if (!(0, utils_js_1.isDuration)(value)) { + throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); + } + } + } + return value; + } + function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { + var _a; + if (!Array.isArray(object)) { + throw new Error(`${objectName} must be of type Array.`); + } + let elementType = mapper.type.element; + if (!elementType || typeof elementType !== "object") { + throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}.`); + } + if (elementType.type.name === "Composite" && elementType.type.className) { + elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType; + } + const tempArray = []; + for (let i = 0; i < object.length; i++) { + const serializedValue = serializer.serialize(elementType, object[i], objectName, options); + if (isXml && elementType.xmlNamespace) { + const xmlnsKey = elementType.xmlNamespacePrefix ? `xmlns:${elementType.xmlNamespacePrefix}` : "xmlns"; + if (elementType.type.name === "Composite") { + tempArray[i] = Object.assign({}, serializedValue); + tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + } else { + tempArray[i] = {}; + tempArray[i][options.xml.xmlCharKey] = serializedValue; + tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + } + } else { + tempArray[i] = serializedValue; + } + } + return tempArray; + } + function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { + if (typeof object !== "object") { + throw new Error(`${objectName} must be of type object.`); + } + const valueType = mapper.type.value; + if (!valueType || typeof valueType !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}.`); + } + const tempDictionary = {}; + for (const key of Object.keys(object)) { + const serializedValue = serializer.serialize(valueType, object[key], objectName, options); + tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); + } + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + const result = tempDictionary; + result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; + return result; + } + return tempDictionary; + } + function resolveAdditionalProperties(serializer, mapper, objectName) { + const additionalProperties = mapper.type.additionalProperties; + if (!additionalProperties && mapper.type.className) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; + } + return additionalProperties; + } + function resolveReferencedMapper(serializer, mapper, objectName) { + const className = mapper.type.className; + if (!className) { + throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, void 0, 2)}".`); + } + return serializer.modelMappers[className]; + } + function resolveModelProperties(serializer, mapper, objectName) { + let modelProps = mapper.type.modelProperties; + if (!modelProps) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + if (!modelMapper) { + throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); + } + modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; + if (!modelProps) { + throw new Error(`modelProperties cannot be null or undefined in the mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); + } + } + return modelProps; + } + function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); + } + if (object !== void 0 && object !== null) { + const payload = {}; + const modelProps = resolveModelProperties(serializer, mapper, objectName); + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + if (propertyMapper.readOnly) { + continue; + } + let propName; + let parentObject = payload; + if (serializer.isXML) { + if (propertyMapper.xmlIsWrapped) { + propName = propertyMapper.xmlName; + } else { + propName = propertyMapper.xmlElementName || propertyMapper.xmlName; + } + } else { + const paths = splitSerializeName(propertyMapper.serializedName); + propName = paths.pop(); + for (const pathName of paths) { + const childObject = parentObject[pathName]; + if ((childObject === void 0 || childObject === null) && (object[key] !== void 0 && object[key] !== null || propertyMapper.defaultValue !== void 0)) { + parentObject[pathName] = {}; + } + parentObject = parentObject[pathName]; + } + } + if (parentObject !== void 0 && parentObject !== null) { + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); + } + const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName; + let toSerialize = object[key]; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && (toSerialize === void 0 || toSerialize === null)) { + toSerialize = mapper.serializedName; + } + const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + if (serializedValue !== void 0 && propName !== void 0 && propName !== null) { + const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + if (isXml && propertyMapper.xmlIsAttribute) { + parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {}; + parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue; + } else if (isXml && propertyMapper.xmlIsWrapped) { + parentObject[propName] = { [propertyMapper.xmlElementName]: value }; + } else { + parentObject[propName] = value; + } + } + } + } + const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); + if (additionalPropertiesMapper) { + const propNames = Object.keys(modelProps); + for (const clientPropName in object) { + const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); + if (isAdditionalProperty) { + payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); + } + } + } + return payload; + } + return object; + } + function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { + if (!isXml || !propertyMapper.xmlNamespace) { + return serializedValue; + } + const xmlnsKey = propertyMapper.xmlNamespacePrefix ? `xmlns:${propertyMapper.xmlNamespacePrefix}` : "xmlns"; + const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; + if (["Composite"].includes(propertyMapper.type.name)) { + if (serializedValue[interfaces_js_1.XML_ATTRKEY]) { + return serializedValue; + } else { + const result2 = Object.assign({}, serializedValue); + result2[interfaces_js_1.XML_ATTRKEY] = xmlNamespace; + return result2; + } + } + const result = {}; + result[options.xml.xmlCharKey] = serializedValue; + result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace; + return result; + } + function isSpecialXmlProperty(propertyName, options) { + return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName); + } + function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { + var _a, _b; + const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY; + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); + } + const modelProps = resolveModelProperties(serializer, mapper, objectName); + let instance = {}; + const handledPropertyNames = []; + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + const paths = splitSerializeName(modelProps[key].serializedName); + handledPropertyNames.push(paths[0]); + const { serializedName, xmlName, xmlElementName } = propertyMapper; + let propertyObjectName = objectName; + if (serializedName !== "" && serializedName !== void 0) { + propertyObjectName = objectName + "." + serializedName; + } + const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; + if (headerCollectionPrefix) { + const dictionary = {}; + for (const headerKey of Object.keys(responseBody)) { + if (headerKey.startsWith(headerCollectionPrefix)) { + dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); + } + handledPropertyNames.push(headerKey); + } + instance[key] = dictionary; + } else if (serializer.isXML) { + if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) { + instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options); + } else if (propertyMapper.xmlIsMsText) { + if (responseBody[xmlCharKey] !== void 0) { + instance[key] = responseBody[xmlCharKey]; + } else if (typeof responseBody === "string") { + instance[key] = responseBody; + } + } else { + const propertyName = xmlElementName || xmlName || serializedName; + if (propertyMapper.xmlIsWrapped) { + const wrapped = responseBody[xmlName]; + const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; + instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); + handledPropertyNames.push(xmlName); + } else { + const property = responseBody[propertyName]; + instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + handledPropertyNames.push(propertyName); + } + } + } else { + let propertyInstance; + let res = responseBody; + let steps = 0; + for (const item of paths) { + if (!res) + break; + steps++; + res = res[item]; + } + if (res === null && steps < paths.length) { + res = void 0; + } + propertyInstance = res; + const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; + if (polymorphicDiscriminator && key === polymorphicDiscriminator.clientName && (propertyInstance === void 0 || propertyInstance === null)) { + propertyInstance = mapper.serializedName; + } + let serializedValue; + if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { + propertyInstance = responseBody[key]; + const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + for (const [k, v] of Object.entries(instance)) { + if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { + arrayInstance[k] = v; + } + } + instance = arrayInstance; + } else if (propertyInstance !== void 0 || propertyMapper.defaultValue !== void 0) { + serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + instance[key] = serializedValue; + } + } + } + const additionalPropertiesMapper = mapper.type.additionalProperties; + if (additionalPropertiesMapper) { + const isAdditionalProperty = (responsePropName) => { + for (const clientPropName in modelProps) { + const paths = splitSerializeName(modelProps[clientPropName].serializedName); + if (paths[0] === responsePropName) { + return false; + } + } + return true; + }; + for (const responsePropName in responseBody) { + if (isAdditionalProperty(responsePropName)) { + instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + } + } + } else if (responseBody && !options.ignoreUnknownProperties) { + for (const key of Object.keys(responseBody)) { + if (instance[key] === void 0 && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { + instance[key] = responseBody[key]; + } + } + } + return instance; + } + function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { + const value = mapper.type.value; + if (!value || typeof value !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + const tempDictionary = {}; + for (const key of Object.keys(responseBody)) { + tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); + } + return tempDictionary; + } + return responseBody; + } + function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { + var _a; + let element = mapper.type.element; + if (!element || typeof element !== "object") { + throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + if (!Array.isArray(responseBody)) { + responseBody = [responseBody]; + } + if (element.type.name === "Composite" && element.type.className) { + element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element; + } + const tempArray = []; + for (let i = 0; i < responseBody.length; i++) { + tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); + } + return tempArray; + } + return responseBody; + } + function getIndexDiscriminator(discriminators, discriminatorValue, typeName) { + const typeNamesToCheck = [typeName]; + while (typeNamesToCheck.length) { + const currentName = typeNamesToCheck.shift(); + const indexDiscriminator = discriminatorValue === currentName ? discriminatorValue : currentName + "." + discriminatorValue; + if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) { + return discriminators[indexDiscriminator]; + } else { + for (const [name, mapper] of Object.entries(discriminators)) { + if (name.startsWith(currentName + ".") && mapper.type.uberParent === currentName && mapper.type.className) { + typeNamesToCheck.push(mapper.type.className); + } + } + } + } + return void 0; + } + function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { + var _a; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator) { + let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; + if (discriminatorName) { + if (polymorphicPropertyName === "serializedName") { + discriminatorName = discriminatorName.replace(/\\/gi, ""); + } + const discriminatorValue = object[discriminatorName]; + const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className; + if (typeof discriminatorValue === "string" && typeName) { + const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName); + if (polymorphicMapper) { + mapper = polymorphicMapper; + } + } + } + } + return mapper; + } + function getPolymorphicDiscriminatorRecursively(serializer, mapper) { + return mapper.type.polymorphicDiscriminator || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className); + } + function getPolymorphicDiscriminatorSafely(serializer, typeName) { + return typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator; + } + exports2.MapperTypeNames = { + Base64Url: "Base64Url", + Boolean: "Boolean", + ByteArray: "ByteArray", + Composite: "Composite", + Date: "Date", + DateTime: "DateTime", + DateTimeRfc1123: "DateTimeRfc1123", + Dictionary: "Dictionary", + Enum: "Enum", + Number: "Number", + Object: "Object", + Sequence: "Sequence", + String: "String", + Stream: "Stream", + TimeSpan: "TimeSpan", + UnixTime: "UnixTime" + }; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/state.js +var require_state2 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/state.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + operationRequestMap: /* @__PURE__ */ new WeakMap() + }; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/operationHelpers.js +var require_operationHelpers = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/operationHelpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getOperationRequestInfo = exports2.getOperationArgumentValueFromParameter = void 0; + var state_js_1 = require_state2(); + function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) { + let parameterPath = parameter.parameterPath; + const parameterMapper = parameter.mapper; + let value; + if (typeof parameterPath === "string") { + parameterPath = [parameterPath]; + } + if (Array.isArray(parameterPath)) { + if (parameterPath.length > 0) { + if (parameterMapper.isConstant) { + value = parameterMapper.defaultValue; + } else { + let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); + if (!propertySearchResult.propertyFound && fallbackObject) { + propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath); + } + let useDefaultValue = false; + if (!propertySearchResult.propertyFound) { + useDefaultValue = parameterMapper.required || parameterPath[0] === "options" && parameterPath.length === 2; + } + value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; + } + } + } else { + if (parameterMapper.required) { + value = {}; + } + for (const propertyName in parameterPath) { + const propertyMapper = parameterMapper.type.modelProperties[propertyName]; + const propertyPath = parameterPath[propertyName]; + const propertyValue = getOperationArgumentValueFromParameter(operationArguments, { + parameterPath: propertyPath, + mapper: propertyMapper + }, fallbackObject); + if (propertyValue !== void 0) { + if (!value) { + value = {}; + } + value[propertyName] = propertyValue; + } + } + } + return value; + } + exports2.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter; + function getPropertyFromParameterPath(parent, parameterPath) { + const result = { propertyFound: false }; + let i = 0; + for (; i < parameterPath.length; ++i) { + const parameterPathPart = parameterPath[i]; + if (parent && parameterPathPart in parent) { + parent = parent[parameterPathPart]; + } else { + break; + } + } + if (i === parameterPath.length) { + result.propertyValue = parent; + result.propertyFound = true; + } + return result; + } + var originalRequestSymbol = Symbol.for("@azure/core-client original request"); + function hasOriginalRequest(request) { + return originalRequestSymbol in request; + } + function getOperationRequestInfo(request) { + if (hasOriginalRequest(request)) { + return getOperationRequestInfo(request[originalRequestSymbol]); + } + let info4 = state_js_1.state.operationRequestMap.get(request); + if (!info4) { + info4 = {}; + state_js_1.state.operationRequestMap.set(request, info4); + } + return info4; + } + exports2.getOperationRequestInfo = getOperationRequestInfo; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/deserializationPolicy.js +var require_deserializationPolicy = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/deserializationPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.deserializationPolicy = exports2.deserializationPolicyName = void 0; + var interfaces_js_1 = require_interfaces(); + var core_rest_pipeline_1 = require_commonjs5(); + var serializer_js_1 = require_serializer(); + var operationHelpers_js_1 = require_operationHelpers(); + var defaultJsonContentTypes = ["application/json", "text/json"]; + var defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; + exports2.deserializationPolicyName = "deserializationPolicy"; + function deserializationPolicy(options = {}) { + var _a, _b, _c, _d, _e, _f, _g; + const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes; + const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes; + const parseXML = options.parseXML; + const serializerOptions = options.serializerOptions; + const updatedOptions = { + xml: { + rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "", + includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false, + xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY + } + }; + return { + name: exports2.deserializationPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML); + } + }; + } + exports2.deserializationPolicy = deserializationPolicy; + function getOperationResponseMap(parsedResponse) { + let result; + const request = parsedResponse.request; + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + if (operationSpec) { + if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) { + result = operationSpec.responses[parsedResponse.status]; + } else { + result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse); + } + } + return result; + } + function shouldDeserializeResponse(parsedResponse) { + const request = parsedResponse.request; + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); + const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize; + let result; + if (shouldDeserialize === void 0) { + result = true; + } else if (typeof shouldDeserialize === "boolean") { + result = shouldDeserialize; + } else { + result = shouldDeserialize(parsedResponse); + } + return result; + } + async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) { + const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML); + if (!shouldDeserializeResponse(parsedResponse)) { + return parsedResponse; + } + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + if (!operationSpec || !operationSpec.responses) { + return parsedResponse; + } + const responseSpec = getOperationResponseMap(parsedResponse); + const { error: error2, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options); + if (error2) { + throw error2; + } else if (shouldReturnResponse) { + return parsedResponse; + } + if (responseSpec) { + if (responseSpec.bodyMapper) { + let valueToDeserialize = parsedResponse.parsedBody; + if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) { + valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : []; + } + try { + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + } catch (deserializeError) { + const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, { + statusCode: parsedResponse.status, + request: parsedResponse.request, + response: parsedResponse + }); + throw restError; + } + } else if (operationSpec.httpMethod === "HEAD") { + parsedResponse.parsedBody = response.status >= 200 && response.status < 300; + } + if (responseSpec.headersMapper) { + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true }); + } + } + return parsedResponse; + } + function isOperationSpecEmpty(operationSpec) { + const expectedStatusCodes = Object.keys(operationSpec.responses); + return expectedStatusCodes.length === 0 || expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"; + } + function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) { + var _a; + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus : !!responseSpec; + if (isExpectedStatusCode) { + if (responseSpec) { + if (!responseSpec.isError) { + return { error: null, shouldReturnResponse: false }; + } + } else { + return { error: null, shouldReturnResponse: false }; + } + } + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText; + const error2 = new core_rest_pipeline_1.RestError(initialErrorMessage, { + statusCode: parsedResponse.status, + request: parsedResponse.request, + response: parsedResponse + }); + if (!errorResponseSpec) { + throw error2; + } + const defaultBodyMapper = errorResponseSpec.bodyMapper; + const defaultHeadersMapper = errorResponseSpec.headersMapper; + try { + if (parsedResponse.parsedBody) { + const parsedBody = parsedResponse.parsedBody; + let deserializedError; + if (defaultBodyMapper) { + let valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) { + valueToDeserialize = []; + const elementName = defaultBodyMapper.xmlElementName; + if (typeof parsedBody === "object" && elementName) { + valueToDeserialize = parsedBody[elementName]; + } + } + deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options); + } + const internalError = parsedBody.error || deserializedError || parsedBody; + error2.code = internalError.code; + if (internalError.message) { + error2.message = internalError.message; + } + if (defaultBodyMapper) { + error2.response.parsedBody = deserializedError; + } + } + if (parsedResponse.headers && defaultHeadersMapper) { + error2.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders"); + } + } catch (defaultError) { + error2.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; + } + return { error: error2, shouldReturnResponse: false }; + } + async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) { + var _a; + if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) && operationResponse.bodyAsText) { + const text = operationResponse.bodyAsText; + const contentType = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType ? [] : contentType.split(";").map((component) => component.toLowerCase()); + try { + if (contentComponents.length === 0 || contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + operationResponse.parsedBody = JSON.parse(text); + return operationResponse; + } else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + if (!parseXML) { + throw new Error("Parsing XML not supported."); + } + const body = await parseXML(text, opts.xml); + operationResponse.parsedBody = body; + return operationResponse; + } + } catch (err) { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR; + const e = new core_rest_pipeline_1.RestError(msg, { + code: errCode, + statusCode: operationResponse.status, + request: operationResponse.request, + response: operationResponse + }); + throw e; + } + } + return operationResponse; + } + } +}); + +// node_modules/@azure/core-client/dist/commonjs/interfaceHelpers.js +var require_interfaceHelpers = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/interfaceHelpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getPathStringFromParameter = exports2.getStreamingResponseStatusCodes = void 0; + var serializer_js_1 = require_serializer(); + function getStreamingResponseStatusCodes(operationSpec) { + const result = /* @__PURE__ */ new Set(); + for (const statusCode in operationSpec.responses) { + const operationResponse = operationSpec.responses[statusCode]; + if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) { + result.add(Number(statusCode)); + } + } + return result; + } + exports2.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes; + function getPathStringFromParameter(parameter) { + const { parameterPath, mapper } = parameter; + let result; + if (typeof parameterPath === "string") { + result = parameterPath; + } else if (Array.isArray(parameterPath)) { + result = parameterPath.join("."); + } else { + result = mapper.serializedName; + } + return result; + } + exports2.getPathStringFromParameter = getPathStringFromParameter; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/serializationPolicy.js +var require_serializationPolicy = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/serializationPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.serializeRequestBody = exports2.serializeHeaders = exports2.serializationPolicy = exports2.serializationPolicyName = void 0; + var interfaces_js_1 = require_interfaces(); + var operationHelpers_js_1 = require_operationHelpers(); + var serializer_js_1 = require_serializer(); + var interfaceHelpers_js_1 = require_interfaceHelpers(); + exports2.serializationPolicyName = "serializationPolicy"; + function serializationPolicy(options = {}) { + const stringifyXML = options.stringifyXML; + return { + name: exports2.serializationPolicyName, + async sendRequest(request, next) { + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments; + if (operationSpec && operationArguments) { + serializeHeaders(request, operationArguments, operationSpec); + serializeRequestBody(request, operationArguments, operationSpec, stringifyXML); + } + return next(request); + } + }; + } + exports2.serializationPolicy = serializationPolicy; + function serializeHeaders(request, operationArguments, operationSpec) { + var _a, _b; + if (operationSpec.headerParameters) { + for (const headerParameter of operationSpec.headerParameters) { + let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter); + if (headerValue !== null && headerValue !== void 0 || headerParameter.mapper.required) { + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter)); + const headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix; + if (headerCollectionPrefix) { + for (const key of Object.keys(headerValue)) { + request.headers.set(headerCollectionPrefix + key, headerValue[key]); + } + } else { + request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue); + } + } + } + } + const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders; + if (customHeaders) { + for (const customHeaderName of Object.keys(customHeaders)) { + request.headers.set(customHeaderName, customHeaders[customHeaderName]); + } + } + } + exports2.serializeHeaders = serializeHeaders; + function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function() { + throw new Error("XML serialization unsupported!"); + }) { + var _a, _b, _c, _d, _e; + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + const updatedOptions = { + xml: { + rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "", + includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false, + xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY + } + }; + const xmlCharKey = updatedOptions.xml.xmlCharKey; + if (operationSpec.requestBody && operationSpec.requestBody.mapper) { + request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody); + const bodyMapper = operationSpec.requestBody.mapper; + const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable } = bodyMapper; + const typeName = bodyMapper.type.name; + try { + if (request.body !== void 0 && request.body !== null || nullable && request.body === null || required) { + const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody); + request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions); + const isStream = typeName === serializer_js_1.MapperTypeNames.Stream; + if (operationSpec.isXML) { + const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; + const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions); + if (typeName === serializer_js_1.MapperTypeNames.Sequence) { + request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey }); + } else if (!isStream) { + request.body = stringifyXML(value, { + rootName: xmlName || serializedName, + xmlCharKey + }); + } + } else if (typeName === serializer_js_1.MapperTypeNames.String && (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) { + return; + } else if (!isStream) { + request.body = JSON.stringify(request.body); + } + } + } catch (error2) { + throw new Error(`Error "${error2.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, void 0, " ")}.`); + } + } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { + request.formData = {}; + for (const formDataParameter of operationSpec.formDataParameters) { + const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter); + if (formDataParameterValue !== void 0 && formDataParameterValue !== null) { + const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter); + request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions); + } + } + } + } + exports2.serializeRequestBody = serializeRequestBody; + function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { + if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { + const result = {}; + result[options.xml.xmlCharKey] = serializedValue; + result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; + return result; + } + return serializedValue; + } + function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { + if (!Array.isArray(obj)) { + obj = [obj]; + } + if (!xmlNamespaceKey || !xmlNamespace) { + return { [elementName]: obj }; + } + const result = { [elementName]: obj }; + result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; + return result; + } + } +}); + +// node_modules/@azure/core-client/dist/commonjs/pipeline.js +var require_pipeline2 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createClientPipeline = void 0; + var deserializationPolicy_js_1 = require_deserializationPolicy(); + var core_rest_pipeline_1 = require_commonjs5(); + var serializationPolicy_js_1 = require_serializationPolicy(); + function createClientPipeline(options = {}) { + const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {}); + if (options.credentialOptions) { + pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({ + credential: options.credentialOptions.credential, + scopes: options.credentialOptions.credentialScopes + })); + } + pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" }); + pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), { + phase: "Deserialize" + }); + return pipeline; + } + exports2.createClientPipeline = createClientPipeline; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/httpClientCache.js +var require_httpClientCache = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/httpClientCache.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getCachedDefaultHttpClient = void 0; + var core_rest_pipeline_1 = require_commonjs5(); + var cachedHttpClient; + function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)(); + } + return cachedHttpClient; + } + exports2.getCachedDefaultHttpClient = getCachedDefaultHttpClient; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/urlHelpers.js +var require_urlHelpers = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/urlHelpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.appendQueryParams = exports2.getRequestUrl = void 0; + var operationHelpers_js_1 = require_operationHelpers(); + var interfaceHelpers_js_1 = require_interfaceHelpers(); + var CollectionFormatToDelimiterMap = { + CSV: ",", + SSV: " ", + Multi: "Multi", + TSV: " ", + Pipes: "|" + }; + function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) { + const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject); + let isAbsolutePath = false; + let requestUrl = replaceAll(baseUri, urlReplacements); + if (operationSpec.path) { + let path2 = replaceAll(operationSpec.path, urlReplacements); + if (operationSpec.path === "/{nextLink}" && path2.startsWith("/")) { + path2 = path2.substring(1); + } + if (isAbsoluteUrl(path2)) { + requestUrl = path2; + isAbsolutePath = true; + } else { + requestUrl = appendPath(requestUrl, path2); + } + } + const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject); + requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath); + return requestUrl; + } + exports2.getRequestUrl = getRequestUrl; + function replaceAll(input, replacements) { + let result = input; + for (const [searchValue, replaceValue] of replacements) { + result = result.split(searchValue).join(replaceValue); + } + return result; + } + function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) { + var _a; + const result = /* @__PURE__ */ new Map(); + if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) { + for (const urlParameter of operationSpec.urlParameters) { + let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject); + const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString); + if (!urlParameter.skipEncoding) { + urlParameterValue = encodeURIComponent(urlParameterValue); + } + result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue); + } + } + return result; + } + function isAbsoluteUrl(url) { + return url.includes("://"); + } + function appendPath(url, pathToAppend) { + if (!pathToAppend) { + return url; + } + const parsedUrl = new URL(url); + let newPath = parsedUrl.pathname; + if (!newPath.endsWith("/")) { + newPath = `${newPath}/`; + } + if (pathToAppend.startsWith("/")) { + pathToAppend = pathToAppend.substring(1); + } + const searchStart = pathToAppend.indexOf("?"); + if (searchStart !== -1) { + const path2 = pathToAppend.substring(0, searchStart); + const search = pathToAppend.substring(searchStart + 1); + newPath = newPath + path2; + if (search) { + parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search; + } + } else { + newPath = newPath + pathToAppend; + } + parsedUrl.pathname = newPath; + return parsedUrl.toString(); + } + function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) { + var _a; + const result = /* @__PURE__ */ new Map(); + const sequenceParams = /* @__PURE__ */ new Set(); + if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) { + for (const queryParameter of operationSpec.queryParameters) { + if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) { + sequenceParams.add(queryParameter.mapper.serializedName); + } + let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject); + if (queryParameterValue !== void 0 && queryParameterValue !== null || queryParameter.mapper.required) { + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter)); + const delimiter = queryParameter.collectionFormat ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat] : ""; + if (Array.isArray(queryParameterValue)) { + queryParameterValue = queryParameterValue.map((item) => { + if (item === null || item === void 0) { + return ""; + } + return item; + }); + } + if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) { + continue; + } else if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) { + queryParameterValue = queryParameterValue.join(delimiter); + } + if (!queryParameter.skipEncoding) { + if (Array.isArray(queryParameterValue)) { + queryParameterValue = queryParameterValue.map((item) => { + return encodeURIComponent(item); + }); + } else { + queryParameterValue = encodeURIComponent(queryParameterValue); + } + } + if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) { + queryParameterValue = queryParameterValue.join(delimiter); + } + result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue); + } + } + } + return { + queryParams: result, + sequenceParams + }; + } + function simpleParseQueryParams(queryString) { + const result = /* @__PURE__ */ new Map(); + if (!queryString || queryString[0] !== "?") { + return result; + } + queryString = queryString.slice(1); + const pairs2 = queryString.split("&"); + for (const pair of pairs2) { + const [name, value] = pair.split("=", 2); + const existingValue = result.get(name); + if (existingValue) { + if (Array.isArray(existingValue)) { + existingValue.push(value); + } else { + result.set(name, [existingValue, value]); + } + } else { + result.set(name, value); + } + } + return result; + } + function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) { + if (queryParams.size === 0) { + return url; + } + const parsedUrl = new URL(url); + const combinedParams = simpleParseQueryParams(parsedUrl.search); + for (const [name, value] of queryParams) { + const existingValue = combinedParams.get(name); + if (Array.isArray(existingValue)) { + if (Array.isArray(value)) { + existingValue.push(...value); + const valueSet = new Set(existingValue); + combinedParams.set(name, Array.from(valueSet)); + } else { + existingValue.push(value); + } + } else if (existingValue) { + if (Array.isArray(value)) { + value.unshift(existingValue); + } else if (sequenceParams.has(name)) { + combinedParams.set(name, [existingValue, value]); + } + if (!noOverwrite) { + combinedParams.set(name, value); + } + } else { + combinedParams.set(name, value); + } + } + const searchPieces = []; + for (const [name, value] of combinedParams) { + if (typeof value === "string") { + searchPieces.push(`${name}=${value}`); + } else if (Array.isArray(value)) { + for (const subValue of value) { + searchPieces.push(`${name}=${subValue}`); + } + } else { + searchPieces.push(`${name}=${value}`); + } + } + parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return parsedUrl.toString(); + } + exports2.appendQueryParams = appendQueryParams; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/log.js +var require_log3 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/log.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-client"); + } +}); + +// node_modules/@azure/core-client/dist/commonjs/serviceClient.js +var require_serviceClient = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/serviceClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServiceClient = void 0; + var core_rest_pipeline_1 = require_commonjs5(); + var pipeline_js_1 = require_pipeline2(); + var utils_js_1 = require_utils5(); + var httpClientCache_js_1 = require_httpClientCache(); + var operationHelpers_js_1 = require_operationHelpers(); + var urlHelpers_js_1 = require_urlHelpers(); + var interfaceHelpers_js_1 = require_interfaceHelpers(); + var log_js_1 = require_log3(); + var ServiceClient = class { + /** + * The ServiceClient constructor + * @param credential - The credentials used for authentication with the service. + * @param options - The service client options that govern the behavior of the client. + */ + constructor(options = {}) { + var _a, _b; + this._requestContentType = options.requestContentType; + this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri; + if (options.baseUri) { + log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."); + } + this._allowInsecureConnection = options.allowInsecureConnection; + this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)(); + this.pipeline = options.pipeline || createDefaultPipeline(options); + if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) { + for (const { policy, position } of options.additionalPolicies) { + const afterPhase = position === "perRetry" ? "Sign" : void 0; + this.pipeline.addPolicy(policy, { + afterPhase + }); + } + } + } + /** + * Send the provided httpRequest. + */ + async sendRequest(request) { + return this.pipeline.sendRequest(this._httpClient, request); + } + /** + * Send an HTTP request that is populated using the provided OperationSpec. + * @typeParam T - The typed result of the request, based on the OperationSpec. + * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. + * @param operationSpec - The OperationSpec to use to populate the httpRequest. + */ + async sendOperationRequest(operationArguments, operationSpec) { + const endpoint = operationSpec.baseUrl || this._endpoint; + if (!endpoint) { + throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use."); + } + const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this); + const request = (0, core_rest_pipeline_1.createPipelineRequest)({ + url + }); + request.method = operationSpec.httpMethod; + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); + operationInfo.operationSpec = operationSpec; + operationInfo.operationArguments = operationArguments; + const contentType = operationSpec.contentType || this._requestContentType; + if (contentType && operationSpec.requestBody) { + request.headers.set("Content-Type", contentType); + } + const options = operationArguments.options; + if (options) { + const requestOptions = options.requestOptions; + if (requestOptions) { + if (requestOptions.timeout) { + request.timeout = requestOptions.timeout; + } + if (requestOptions.onUploadProgress) { + request.onUploadProgress = requestOptions.onUploadProgress; + } + if (requestOptions.onDownloadProgress) { + request.onDownloadProgress = requestOptions.onDownloadProgress; + } + if (requestOptions.shouldDeserialize !== void 0) { + operationInfo.shouldDeserialize = requestOptions.shouldDeserialize; + } + if (requestOptions.allowInsecureConnection) { + request.allowInsecureConnection = true; + } + } + if (options.abortSignal) { + request.abortSignal = options.abortSignal; + } + if (options.tracingOptions) { + request.tracingOptions = options.tracingOptions; + } + } + if (this._allowInsecureConnection) { + request.allowInsecureConnection = true; + } + if (request.streamResponseStatusCodes === void 0) { + request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec); + } + try { + const rawResponse = await this.sendRequest(request); + const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]); + if (options === null || options === void 0 ? void 0 : options.onResponse) { + options.onResponse(rawResponse, flatResponse); + } + return flatResponse; + } catch (error2) { + if (typeof error2 === "object" && (error2 === null || error2 === void 0 ? void 0 : error2.response)) { + const rawResponse = error2.response; + const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error2.statusCode] || operationSpec.responses["default"]); + error2.details = flatResponse; + if (options === null || options === void 0 ? void 0 : options.onResponse) { + options.onResponse(rawResponse, flatResponse, error2); + } + } + throw error2; + } + } + }; + exports2.ServiceClient = ServiceClient; + function createDefaultPipeline(options) { + const credentialScopes = getCredentialScopes(options); + const credentialOptions = options.credential && credentialScopes ? { credentialScopes, credential: options.credential } : void 0; + return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions })); + } + function getCredentialScopes(options) { + if (options.credentialScopes) { + return options.credentialScopes; + } + if (options.endpoint) { + return `${options.endpoint}/.default`; + } + if (options.baseUri) { + return `${options.baseUri}/.default`; + } + if (options.credential && !options.credentialScopes) { + throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`); + } + return void 0; + } + } +}); + +// node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnClaimChallenge.js +var require_authorizeRequestOnClaimChallenge = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnClaimChallenge.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.authorizeRequestOnClaimChallenge = exports2.parseCAEChallenge = void 0; + var log_js_1 = require_log3(); + var base64_js_1 = require_base64(); + function parseCAEChallenge(challenges) { + const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x); + return bearerChallenges.map((challenge) => { + const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x); + const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="'))); + return keyValuePairs.reduce((a, b) => Object.assign(Object.assign({}, a), b), {}); + }); + } + exports2.parseCAEChallenge = parseCAEChallenge; + async function authorizeRequestOnClaimChallenge(onChallengeOptions) { + const { scopes, response } = onChallengeOptions; + const logger = onChallengeOptions.logger || log_js_1.logger; + const challenge = response.headers.get("WWW-Authenticate"); + if (!challenge) { + logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`); + return false; + } + const challenges = parseCAEChallenge(challenge) || []; + const parsedChallenge = challenges.find((x) => x.claims); + if (!parsedChallenge) { + logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`); + return false; + } + const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, { + claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims) + }); + if (!accessToken) { + return false; + } + onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + return true; + } + exports2.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnTenantChallenge.js +var require_authorizeRequestOnTenantChallenge = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnTenantChallenge.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.authorizeRequestOnTenantChallenge = void 0; + var Constants = { + DefaultScope: "/.default", + /** + * Defines constants for use with HTTP headers. + */ + HeaderConstants: { + /** + * The Authorization header. + */ + AUTHORIZATION: "authorization" + } + }; + function isUuid(text) { + return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text); + } + var authorizeRequestOnTenantChallenge = async (challengeOptions) => { + const requestOptions = requestToOptions(challengeOptions.request); + const challenge = getChallenge(challengeOptions.response); + if (challenge) { + const challengeInfo = parseChallenge(challenge); + const challengeScopes = buildScopes(challengeOptions, challengeInfo); + const tenantId = extractTenantId(challengeInfo); + if (!tenantId) { + return false; + } + const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId })); + if (!accessToken) { + return false; + } + challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`); + return true; + } + return false; + }; + exports2.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge; + function extractTenantId(challengeInfo) { + const parsedAuthUri = new URL(challengeInfo.authorization_uri); + const pathSegments = parsedAuthUri.pathname.split("/"); + const tenantId = pathSegments[1]; + if (tenantId && isUuid(tenantId)) { + return tenantId; + } + return void 0; + } + function buildScopes(challengeOptions, challengeInfo) { + if (!challengeInfo.resource_id) { + return challengeOptions.scopes; + } + const challengeScopes = new URL(challengeInfo.resource_id); + challengeScopes.pathname = Constants.DefaultScope; + let scope = challengeScopes.toString(); + if (scope === "https://disk.azure.com/.default") { + scope = "https://disk.azure.com//.default"; + } + return [scope]; + } + function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; + } + return; + } + function parseChallenge(challenge) { + const bearerChallenge = challenge.slice("Bearer ".length); + const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x); + const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("="))); + return keyValuePairs.reduce((a, b) => Object.assign(Object.assign({}, a), b), {}); + } + function requestToOptions(request) { + return { + abortSignal: request.abortSignal, + requestOptions: { + timeout: request.timeout + }, + tracingOptions: request.tracingOptions + }; + } + } +}); + +// node_modules/@azure/core-client/dist/commonjs/index.js +var require_commonjs7 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.authorizeRequestOnTenantChallenge = exports2.authorizeRequestOnClaimChallenge = exports2.serializationPolicyName = exports2.serializationPolicy = exports2.deserializationPolicyName = exports2.deserializationPolicy = exports2.XML_CHARKEY = exports2.XML_ATTRKEY = exports2.createClientPipeline = exports2.ServiceClient = exports2.MapperTypeNames = exports2.createSerializer = void 0; + var serializer_js_1 = require_serializer(); + Object.defineProperty(exports2, "createSerializer", { enumerable: true, get: function() { + return serializer_js_1.createSerializer; + } }); + Object.defineProperty(exports2, "MapperTypeNames", { enumerable: true, get: function() { + return serializer_js_1.MapperTypeNames; + } }); + var serviceClient_js_1 = require_serviceClient(); + Object.defineProperty(exports2, "ServiceClient", { enumerable: true, get: function() { + return serviceClient_js_1.ServiceClient; + } }); + var pipeline_js_1 = require_pipeline2(); + Object.defineProperty(exports2, "createClientPipeline", { enumerable: true, get: function() { + return pipeline_js_1.createClientPipeline; + } }); + var interfaces_js_1 = require_interfaces(); + Object.defineProperty(exports2, "XML_ATTRKEY", { enumerable: true, get: function() { + return interfaces_js_1.XML_ATTRKEY; + } }); + Object.defineProperty(exports2, "XML_CHARKEY", { enumerable: true, get: function() { + return interfaces_js_1.XML_CHARKEY; + } }); + var deserializationPolicy_js_1 = require_deserializationPolicy(); + Object.defineProperty(exports2, "deserializationPolicy", { enumerable: true, get: function() { + return deserializationPolicy_js_1.deserializationPolicy; + } }); + Object.defineProperty(exports2, "deserializationPolicyName", { enumerable: true, get: function() { + return deserializationPolicy_js_1.deserializationPolicyName; + } }); + var serializationPolicy_js_1 = require_serializationPolicy(); + Object.defineProperty(exports2, "serializationPolicy", { enumerable: true, get: function() { + return serializationPolicy_js_1.serializationPolicy; + } }); + Object.defineProperty(exports2, "serializationPolicyName", { enumerable: true, get: function() { + return serializationPolicy_js_1.serializationPolicyName; + } }); + var authorizeRequestOnClaimChallenge_js_1 = require_authorizeRequestOnClaimChallenge(); + Object.defineProperty(exports2, "authorizeRequestOnClaimChallenge", { enumerable: true, get: function() { + return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; + } }); + var authorizeRequestOnTenantChallenge_js_1 = require_authorizeRequestOnTenantChallenge(); + Object.defineProperty(exports2, "authorizeRequestOnTenantChallenge", { enumerable: true, get: function() { + return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; + } }); + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/util.js +var require_util9 = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/util.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpHeaders = exports2.toHttpHeadersLike = exports2.toWebResourceLike = exports2.toPipelineRequest = void 0; + var core_rest_pipeline_1 = require_commonjs5(); + var originalRequestSymbol = Symbol("Original PipelineRequest"); + var originalClientRequestSymbol = Symbol.for("@azure/core-client original request"); + function toPipelineRequest(webResource, options = {}) { + const compatWebResource = webResource; + const request = compatWebResource[originalRequestSymbol]; + const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true })); + if (request) { + request.headers = headers; + return request; + } else { + const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({ + url: webResource.url, + method: webResource.method, + headers, + withCredentials: webResource.withCredentials, + timeout: webResource.timeout, + requestId: webResource.requestId, + abortSignal: webResource.abortSignal, + body: webResource.body, + formData: webResource.formData, + disableKeepAlive: !!webResource.keepAlive, + onDownloadProgress: webResource.onDownloadProgress, + onUploadProgress: webResource.onUploadProgress, + proxySettings: webResource.proxySettings, + streamResponseStatusCodes: webResource.streamResponseStatusCodes + }); + if (options.originalRequest) { + newRequest[originalClientRequestSymbol] = options.originalRequest; + } + return newRequest; + } + } + exports2.toPipelineRequest = toPipelineRequest; + function toWebResourceLike(request, options) { + var _a; + const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request; + const webResource = { + url: request.url, + method: request.method, + headers: toHttpHeadersLike(request.headers), + withCredentials: request.withCredentials, + timeout: request.timeout, + requestId: request.headers.get("x-ms-client-request-id") || request.requestId, + abortSignal: request.abortSignal, + body: request.body, + formData: request.formData, + keepAlive: !!request.disableKeepAlive, + onDownloadProgress: request.onDownloadProgress, + onUploadProgress: request.onUploadProgress, + proxySettings: request.proxySettings, + streamResponseStatusCodes: request.streamResponseStatusCodes, + clone() { + throw new Error("Cannot clone a non-proxied WebResourceLike"); + }, + prepare() { + throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat"); + }, + validateRequestProperties() { + } + }; + if (options === null || options === void 0 ? void 0 : options.createProxy) { + return new Proxy(webResource, { + get(target, prop, receiver) { + if (prop === originalRequestSymbol) { + return request; + } else if (prop === "clone") { + return () => { + return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), { + createProxy: true, + originalRequest + }); + }; + } + return Reflect.get(target, prop, receiver); + }, + set(target, prop, value, receiver) { + if (prop === "keepAlive") { + request.disableKeepAlive = !value; + } + const passThroughProps = [ + "url", + "method", + "withCredentials", + "timeout", + "requestId", + "abortSignal", + "body", + "formData", + "onDownloadProgress", + "onUploadProgress", + "proxySettings", + "streamResponseStatusCodes" + ]; + if (typeof prop === "string" && passThroughProps.includes(prop)) { + request[prop] = value; + } + return Reflect.set(target, prop, value, receiver); + } + }); + } else { + return webResource; + } + } + exports2.toWebResourceLike = toWebResourceLike; + function toHttpHeadersLike(headers) { + return new HttpHeaders(headers.toJSON({ preserveCase: true })); + } + exports2.toHttpHeadersLike = toHttpHeadersLike; + function getHeaderKey(headerName) { + return headerName.toLowerCase(); + } + var HttpHeaders = class _HttpHeaders { + constructor(rawHeaders) { + this._headersMap = {}; + if (rawHeaders) { + for (const headerName in rawHeaders) { + this.set(headerName, rawHeaders[headerName]); + } + } + } + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param headerName - The name of the header to set. This value is case-insensitive. + * @param headerValue - The value of the header to set. + */ + set(headerName, headerValue) { + this._headersMap[getHeaderKey(headerName)] = { + name: headerName, + value: headerValue.toString() + }; + } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param headerName - The name of the header. + */ + get(headerName) { + const header = this._headersMap[getHeaderKey(headerName)]; + return !header ? void 0 : header.value; + } + /** + * Get whether or not this header collection contains a header entry for the provided header name. + */ + contains(headerName) { + return !!this._headersMap[getHeaderKey(headerName)]; + } + /** + * Remove the header with the provided headerName. Return whether or not the header existed and + * was removed. + * @param headerName - The name of the header to remove. + */ + remove(headerName) { + const result = this.contains(headerName); + delete this._headersMap[getHeaderKey(headerName)]; + return result; + } + /** + * Get the headers that are contained this collection as an object. + */ + rawHeaders() { + return this.toJson({ preserveCase: true }); + } + /** + * Get the headers that are contained in this collection as an array. + */ + headersArray() { + const headers = []; + for (const headerKey in this._headersMap) { + headers.push(this._headersMap[headerKey]); + } + return headers; + } + /** + * Get the header names that are contained in this collection. + */ + headerNames() { + const headerNames = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { + headerNames.push(headers[i].name); + } + return headerNames; + } + /** + * Get the header values that are contained in this collection. + */ + headerValues() { + const headerValues = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { + headerValues.push(headers[i].value); + } + return headerValues; + } + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJson(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[header.name] = header.value; + } + } else { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[getHeaderKey(header.name)] = header.value; + } + } + return result; + } + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJson({ preserveCase: true })); + } + /** + * Create a deep clone/copy of this HttpHeaders collection. + */ + clone() { + const resultPreservingCasing = {}; + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + resultPreservingCasing[header.name] = header.value; + } + return new _HttpHeaders(resultPreservingCasing); + } + }; + exports2.HttpHeaders = HttpHeaders; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/response.js +var require_response2 = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/response.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.toPipelineResponse = exports2.toCompatResponse = void 0; + var core_rest_pipeline_1 = require_commonjs5(); + var util_js_1 = require_util9(); + var originalResponse = Symbol("Original FullOperationResponse"); + function toCompatResponse(response, options) { + let request = (0, util_js_1.toWebResourceLike)(response.request); + let headers = (0, util_js_1.toHttpHeadersLike)(response.headers); + if (options === null || options === void 0 ? void 0 : options.createProxy) { + return new Proxy(response, { + get(target, prop, receiver) { + if (prop === "headers") { + return headers; + } else if (prop === "request") { + return request; + } else if (prop === originalResponse) { + return response; + } + return Reflect.get(target, prop, receiver); + }, + set(target, prop, value, receiver) { + if (prop === "headers") { + headers = value; + } else if (prop === "request") { + request = value; + } + return Reflect.set(target, prop, value, receiver); + } + }); + } else { + return Object.assign(Object.assign({}, response), { + request, + headers + }); + } + } + exports2.toCompatResponse = toCompatResponse; + function toPipelineResponse(compatResponse) { + const extendedCompatResponse = compatResponse; + const response = extendedCompatResponse[originalResponse]; + const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true })); + if (response) { + response.headers = headers; + return response; + } else { + return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) }); + } + } + exports2.toPipelineResponse = toPipelineResponse; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js +var require_extendedClient = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ExtendedServiceClient = void 0; + var disableKeepAlivePolicy_js_1 = require_disableKeepAlivePolicy(); + var core_rest_pipeline_1 = require_commonjs5(); + var core_client_1 = require_commonjs7(); + var response_js_1 = require_response2(); + var ExtendedServiceClient = class extends core_client_1.ServiceClient { + constructor(options) { + var _a, _b; + super(options); + if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false && !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) { + this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)()); + } + if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) { + this.pipeline.removePolicy({ + name: core_rest_pipeline_1.redirectPolicyName + }); + } + } + /** + * Compatible send operation request function. + * + * @param operationArguments - Operation arguments + * @param operationSpec - Operation Spec + * @returns + */ + async sendOperationRequest(operationArguments, operationSpec) { + var _a; + const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse; + let lastResponse; + function onResponse(rawResponse, flatResponse, error2) { + lastResponse = rawResponse; + if (userProvidedCallBack) { + userProvidedCallBack(rawResponse, flatResponse, error2); + } + } + operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse }); + const result = await super.sendOperationRequest(operationArguments, operationSpec); + if (lastResponse) { + Object.defineProperty(result, "_response", { + value: (0, response_js_1.toCompatResponse)(lastResponse) + }); + } + return result; + } + }; + exports2.ExtendedServiceClient = ExtendedServiceClient; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js +var require_requestPolicyFactoryPolicy = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createRequestPolicyFactoryPolicy = exports2.requestPolicyFactoryPolicyName = exports2.HttpPipelineLogLevel = void 0; + var util_js_1 = require_util9(); + var response_js_1 = require_response2(); + var HttpPipelineLogLevel; + (function(HttpPipelineLogLevel2) { + HttpPipelineLogLevel2[HttpPipelineLogLevel2["ERROR"] = 1] = "ERROR"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["INFO"] = 3] = "INFO"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["OFF"] = 0] = "OFF"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["WARNING"] = 2] = "WARNING"; + })(HttpPipelineLogLevel || (exports2.HttpPipelineLogLevel = HttpPipelineLogLevel = {})); + var mockRequestPolicyOptions = { + log(_logLevel, _message) { + }, + shouldLog(_logLevel) { + return false; + } + }; + exports2.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy"; + function createRequestPolicyFactoryPolicy(factories) { + const orderedFactories = factories.slice().reverse(); + return { + name: exports2.requestPolicyFactoryPolicyName, + async sendRequest(request, next) { + let httpPipeline = { + async sendRequest(httpRequest) { + const response2 = await next((0, util_js_1.toPipelineRequest)(httpRequest)); + return (0, response_js_1.toCompatResponse)(response2, { createProxy: true }); + } + }; + for (const factory of orderedFactories) { + httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions); + } + const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true }); + const response = await httpPipeline.sendRequest(webResourceLike); + return (0, response_js_1.toPipelineResponse)(response); + } + }; + } + exports2.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js +var require_httpClientAdapter = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.convertHttpClient = void 0; + var response_js_1 = require_response2(); + var util_js_1 = require_util9(); + function convertHttpClient(requestPolicyClient) { + return { + sendRequest: async (request) => { + const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true })); + return (0, response_js_1.toPipelineResponse)(response); + } + }; + } + exports2.convertHttpClient = convertHttpClient; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/index.js +var require_commonjs8 = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.toHttpHeadersLike = exports2.convertHttpClient = exports2.disableKeepAlivePolicyName = exports2.HttpPipelineLogLevel = exports2.createRequestPolicyFactoryPolicy = exports2.requestPolicyFactoryPolicyName = exports2.ExtendedServiceClient = void 0; + var extendedClient_js_1 = require_extendedClient(); + Object.defineProperty(exports2, "ExtendedServiceClient", { enumerable: true, get: function() { + return extendedClient_js_1.ExtendedServiceClient; + } }); + var requestPolicyFactoryPolicy_js_1 = require_requestPolicyFactoryPolicy(); + Object.defineProperty(exports2, "requestPolicyFactoryPolicyName", { enumerable: true, get: function() { + return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; + } }); + Object.defineProperty(exports2, "createRequestPolicyFactoryPolicy", { enumerable: true, get: function() { + return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; + } }); + Object.defineProperty(exports2, "HttpPipelineLogLevel", { enumerable: true, get: function() { + return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; + } }); + var disableKeepAlivePolicy_js_1 = require_disableKeepAlivePolicy(); + Object.defineProperty(exports2, "disableKeepAlivePolicyName", { enumerable: true, get: function() { + return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; + } }); + var httpClientAdapter_js_1 = require_httpClientAdapter(); + Object.defineProperty(exports2, "convertHttpClient", { enumerable: true, get: function() { + return httpClientAdapter_js_1.convertHttpClient; + } }); + var util_js_1 = require_util9(); + Object.defineProperty(exports2, "toHttpHeadersLike", { enumerable: true, get: function() { + return util_js_1.toHttpHeadersLike; + } }); + } +}); + +// node_modules/fast-xml-parser/src/util.js +var require_util10 = __commonJS({ + "node_modules/fast-xml-parser/src/util.js"(exports2) { + "use strict"; + var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; + var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; + var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; + var regexName = new RegExp("^" + nameRegexp + "$"); + var getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; + }; + var isName = function(string) { + const match = regexName.exec(string); + return !(match === null || typeof match === "undefined"); + }; + exports2.isExist = function(v) { + return typeof v !== "undefined"; + }; + exports2.isEmptyObject = function(obj) { + return Object.keys(obj).length === 0; + }; + exports2.merge = function(target, a, arrayMode) { + if (a) { + const keys = Object.keys(a); + const len = keys.length; + for (let i = 0; i < len; i++) { + if (arrayMode === "strict") { + target[keys[i]] = [a[keys[i]]]; + } else { + target[keys[i]] = a[keys[i]]; + } + } + } + }; + exports2.getValue = function(v) { + if (exports2.isExist(v)) { + return v; + } else { + return ""; + } + }; + exports2.isName = isName; + exports2.getAllMatches = getAllMatches; + exports2.nameRegexp = nameRegexp; + } +}); + +// node_modules/fast-xml-parser/src/validator.js +var require_validator = __commonJS({ + "node_modules/fast-xml-parser/src/validator.js"(exports2) { + "use strict"; + var util = require_util10(); + var defaultOptions = { + allowBooleanAttributes: false, + //A tag can have attributes without any value + unpairedTags: [] + }; + exports2.validate = function(xmlData, options) { + options = Object.assign({}, defaultOptions, options); + const tags = []; + let tagFound = false; + let reachedRoot = false; + if (xmlData[0] === "\uFEFF") { + xmlData = xmlData.substr(1); + } + for (let i = 0; i < xmlData.length; i++) { + if (xmlData[i] === "<" && xmlData[i + 1] === "?") { + i += 2; + i = readPI(xmlData, i); + if (i.err) return i; + } else if (xmlData[i] === "<") { + let tagStartPos = i; + i++; + if (xmlData[i] === "!") { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === "/") { + closingTag = true; + i++; + } + let tagName = ""; + for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== " " && xmlData[i] !== "\n" && xmlData[i] !== "\r"; i++) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substring(0, tagName.length - 1); + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '" + tagName + "' is an invalid name."; + } + return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i)); + } + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + if (attrStr[attrStr.length - 1] === "/") { + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + } else { + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject( + "InvalidTag", + "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", + getLineNumberForPosition(xmlData, tagStartPos) + ); + } + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + if (reachedRoot === true) { + return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i)); + } else if (options.unpairedTags.indexOf(tagName) !== -1) { + } else { + tags.push({ tagName, tagStartPos }); + } + tagFound = true; + } + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + if (xmlData[i + 1] === "!") { + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i + 1] === "?") { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else { + break; + } + } else if (xmlData[i] === "&") { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + } else { + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } + if (xmlData[i] === "<") { + i--; + } + } + } else { + if (isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i)); + } + } + if (!tagFound) { + return getErrorObject("InvalidXml", "Start tag expected.", 1); + } else if (tags.length == 1) { + return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + } else if (tags.length > 0) { + return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }); + } + return true; + }; + function isWhiteSpace(char) { + return char === " " || char === " " || char === "\n" || char === "\r"; + } + function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == "?" || xmlData[i] == " ") { + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === "xml") { + return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == "?" && xmlData[i + 1] == ">") { + i++; + break; + } else { + continue; + } + } + } + return i; + } + function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") { + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") { + i += 2; + break; + } + } + } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + angleBracketsCount++; + } else if (xmlData[i] === ">") { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") { + i += 2; + break; + } + } + } + return i; + } + var doubleQuote = '"'; + var singleQuote = "'"; + function readAttributeStr(xmlData, i) { + let attrStr = ""; + let startChar = ""; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === "") { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + } else { + startChar = ""; + } + } else if (xmlData[i] === ">") { + if (startChar === "") { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== "") { + return false; + } + return { + value: attrStr, + index: i, + tagClosed + }; + } + var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); + function validateAttributeString(attrStr, options) { + const matches = util.getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] !== void 0 && matches[i][4] === void 0) { + return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === void 0 && !options.allowBooleanAttributes) { + return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i])); + } + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!attrNames.hasOwnProperty(attrName)) { + attrNames[attrName] = 1; + } else { + return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i])); + } + } + return true; + } + function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === "x") { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ";") + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; + } + function validateAmpersand(xmlData, i) { + i++; + if (xmlData[i] === ";") + return -1; + if (xmlData[i] === "#") { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ";") + break; + return -1; + } + return i; + } + function getErrorObject(code, message, lineNumber) { + return { + err: { + code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col + } + }; + } + function validateAttrName(attrName) { + return util.isName(attrName); + } + function validateTagName(tagname) { + return util.isName(tagname); + } + function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; + } + function getPositionFromMatch(match) { + return match.startIndex + match[1].length; + } + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js +var require_OptionsBuilder = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) { + var defaultOptions = { + preserveOrder: false, + attributeNamePrefix: "@_", + attributesGroupName: false, + textNodeName: "#text", + ignoreAttributes: true, + removeNSPrefix: false, + // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, + //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, + //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true + }, + tagValueProcessor: function(tagName, val2) { + return val2; + }, + attributeValueProcessor: function(attrName, val2) { + return val2; + }, + stopNodes: [], + //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function(tagName, jPath, attrs) { + return tagName; + } + // skipEmptyListItem: false + }; + var buildOptions = function(options) { + return Object.assign({}, defaultOptions, options); + }; + exports2.buildOptions = buildOptions; + exports2.defaultOptions = defaultOptions; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/xmlNode.js +var require_xmlNode = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports2, module2) { + "use strict"; + var XmlNode = class { + constructor(tagname) { + this.tagname = tagname; + this.child = []; + this[":@"] = {}; + } + add(key, val2) { + if (key === "__proto__") key = "#__proto__"; + this.child.push({ [key]: val2 }); + } + addChild(node) { + if (node.tagname === "__proto__") node.tagname = "#__proto__"; + if (node[":@"] && Object.keys(node[":@"]).length > 0) { + this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); + } else { + this.child.push({ [node.tagname]: node.child }); + } + } + }; + module2.exports = XmlNode; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js +var require_DocTypeReader = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module2) { + var util = require_util10(); + function readDocType(xmlData, i) { + const entities = {}; + if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") { + i = i + 9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for (; i < xmlData.length; i++) { + if (xmlData[i] === "<" && !comment) { + if (hasBody && isEntity(xmlData, i)) { + i += 7; + [entityName, val, i] = readEntityExp(xmlData, i + 1); + if (val.indexOf("&") === -1) + entities[validateEntityName(entityName)] = { + regx: RegExp(`&${entityName};`, "g"), + val + }; + } else if (hasBody && isElement(xmlData, i)) i += 8; + else if (hasBody && isAttlist(xmlData, i)) i += 8; + else if (hasBody && isNotation(xmlData, i)) i += 9; + else if (isComment) comment = true; + else throw new Error("Invalid DOCTYPE"); + angleBracketsCount++; + exp = ""; + } else if (xmlData[i] === ">") { + if (comment) { + if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") { + comment = false; + angleBracketsCount--; + } + } else { + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + } else if (xmlData[i] === "[") { + hasBody = true; + } else { + exp += xmlData[i]; + } + } + if (angleBracketsCount !== 0) { + throw new Error(`Unclosed DOCTYPE`); + } + } else { + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return { entities, i }; + } + function readEntityExp(xmlData, i) { + let entityName2 = ""; + for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"'); i++) { + entityName2 += xmlData[i]; + } + entityName2 = entityName2.trim(); + if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported"); + const startChar = xmlData[i++]; + let val2 = ""; + for (; i < xmlData.length && xmlData[i] !== startChar; i++) { + val2 += xmlData[i]; + } + return [entityName2, val2, i]; + } + function isComment(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "-" && xmlData[i + 3] === "-") return true; + return false; + } + function isEntity(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "N" && xmlData[i + 4] === "T" && xmlData[i + 5] === "I" && xmlData[i + 6] === "T" && xmlData[i + 7] === "Y") return true; + return false; + } + function isElement(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "L" && xmlData[i + 4] === "E" && xmlData[i + 5] === "M" && xmlData[i + 6] === "E" && xmlData[i + 7] === "N" && xmlData[i + 8] === "T") return true; + return false; + } + function isAttlist(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "A" && xmlData[i + 3] === "T" && xmlData[i + 4] === "T" && xmlData[i + 5] === "L" && xmlData[i + 6] === "I" && xmlData[i + 7] === "S" && xmlData[i + 8] === "T") return true; + return false; + } + function isNotation(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "N" && xmlData[i + 3] === "O" && xmlData[i + 4] === "T" && xmlData[i + 5] === "A" && xmlData[i + 6] === "T" && xmlData[i + 7] === "I" && xmlData[i + 8] === "O" && xmlData[i + 9] === "N") return true; + return false; + } + function validateEntityName(name) { + if (util.isName(name)) + return name; + else + throw new Error(`Invalid entity name ${name}`); + } + module2.exports = readDocType; + } +}); + +// node_modules/strnum/strnum.js +var require_strnum = __commonJS({ + "node_modules/strnum/strnum.js"(exports2, module2) { + var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; + var numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/; + if (!Number.parseInt && window.parseInt) { + Number.parseInt = window.parseInt; + } + if (!Number.parseFloat && window.parseFloat) { + Number.parseFloat = window.parseFloat; + } + var consider = { + hex: true, + leadingZeros: true, + decimalPoint: ".", + eNotation: true + //skipLike: /regex/ + }; + function toNumber(str2, options = {}) { + options = Object.assign({}, consider, options); + if (!str2 || typeof str2 !== "string") return str2; + let trimmedStr = str2.trim(); + if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str2; + else if (options.hex && hexRegex.test(trimmedStr)) { + return Number.parseInt(trimmedStr, 16); + } else { + const match = numRegex.exec(trimmedStr); + if (match) { + const sign = match[1]; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); + const eNotation = match[4] || match[6]; + if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str2; + else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str2; + else { + const num = Number(trimmedStr); + const numStr = "" + num; + if (numStr.search(/[eE]/) !== -1) { + if (options.eNotation) return num; + else return str2; + } else if (eNotation) { + if (options.eNotation) return num; + else return str2; + } else if (trimmedStr.indexOf(".") !== -1) { + if (numStr === "0" && numTrimmedByZeros === "") return num; + else if (numStr === numTrimmedByZeros) return num; + else if (sign && numStr === "-" + numTrimmedByZeros) return num; + else return str2; + } + if (leadingZeros) { + if (numTrimmedByZeros === numStr) return num; + else if (sign + numTrimmedByZeros === numStr) return num; + else return str2; + } + if (trimmedStr === numStr) return num; + else if (trimmedStr === sign + numStr) return num; + return str2; + } + } else { + return str2; + } + } + } + function trimZeros(numStr) { + if (numStr && numStr.indexOf(".") !== -1) { + numStr = numStr.replace(/0+$/, ""); + if (numStr === ".") numStr = "0"; + else if (numStr[0] === ".") numStr = "0" + numStr; + else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1); + return numStr; + } + return numStr; + } + module2.exports = toNumber; + } +}); + +// node_modules/fast-xml-parser/src/ignoreAttributes.js +var require_ignoreAttributes = __commonJS({ + "node_modules/fast-xml-parser/src/ignoreAttributes.js"(exports2, module2) { + function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === "function") { + return ignoreAttributes; + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === "string" && attrName === pattern) { + return true; + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true; + } + } + }; + } + return () => false; + } + module2.exports = getIgnoreAttributesFn; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js +var require_OrderedObjParser = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports2, module2) { + "use strict"; + var util = require_util10(); + var xmlNode = require_xmlNode(); + var readDocType = require_DocTypeReader(); + var toNumber = require_strnum(); + var getIgnoreAttributesFn = require_ignoreAttributes(); + var OrderedObjParser = class { + constructor(options) { + this.options = options; + this.currentNode = null; + this.tagsNodeStack = []; + this.docTypeEntities = {}; + this.lastEntities = { + "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, + "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, + "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, + "quot": { regex: /&(quot|#34|#x22);/g, val: '"' } + }; + this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; + this.htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent": { regex: /&(cent|#162);/g, val: "\xA2" }, + "pound": { regex: /&(pound|#163);/g, val: "\xA3" }, + "yen": { regex: /&(yen|#165);/g, val: "\xA5" }, + "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" }, + "copyright": { regex: /&(copy|#169);/g, val: "\xA9" }, + "reg": { regex: /&(reg|#174);/g, val: "\xAE" }, + "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str2) => String.fromCharCode(Number.parseInt(str2, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str2) => String.fromCharCode(Number.parseInt(str2, 16)) } + }; + this.addExternalEntities = addExternalEntities; + this.parseXml = parseXml; + this.parseTextData = parseTextData; + this.resolveNameSpace = resolveNameSpace; + this.buildAttributesMap = buildAttributesMap; + this.isItStopNode = isItStopNode; + this.replaceEntitiesValue = replaceEntitiesValue; + this.readStopNodeData = readStopNodeData; + this.saveTextToParentTag = saveTextToParentTag; + this.addChild = addChild; + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); + } + }; + function addExternalEntities(externalEntities) { + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.lastEntities[ent] = { + regex: new RegExp("&" + ent + ";", "g"), + val: externalEntities[ent] + }; + } + } + function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { + if (val2 !== void 0) { + if (this.options.trimValues && !dontTrim) { + val2 = val2.trim(); + } + if (val2.length > 0) { + if (!escapeEntities) val2 = this.replaceEntitiesValue(val2); + const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode); + if (newval === null || newval === void 0) { + return val2; + } else if (typeof newval !== typeof val2 || newval !== val2) { + return newval; + } else if (this.options.trimValues) { + return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); + } else { + const trimmedVal = val2.trim(); + if (trimmedVal === val2) { + return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); + } else { + return val2; + } + } + } + } + } + function resolveNameSpace(tagname) { + if (this.options.removeNSPrefix) { + const tags = tagname.split(":"); + const prefix = tagname.charAt(0) === "/" ? "/" : ""; + if (tags[0] === "xmlns") { + return ""; + } + if (tags.length === 2) { + tagname = prefix + tags[1]; + } + } + return tagname; + } + var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); + function buildAttributesMap(attrStr, jPath, tagName) { + if (this.options.ignoreAttributes !== true && typeof attrStr === "string") { + const matches = util.getAllMatches(attrStr, attrsRegx); + const len = matches.length; + const attrs = {}; + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + if (this.ignoreAttributesFn(attrName, jPath)) { + continue; + } + let oldVal = matches[i][4]; + let aName = this.options.attributeNamePrefix + attrName; + if (attrName.length) { + if (this.options.transformAttributeName) { + aName = this.options.transformAttributeName(aName); + } + if (aName === "__proto__") aName = "#__proto__"; + if (oldVal !== void 0) { + if (this.options.trimValues) { + oldVal = oldVal.trim(); + } + oldVal = this.replaceEntitiesValue(oldVal); + const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); + if (newVal === null || newVal === void 0) { + attrs[aName] = oldVal; + } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { + attrs[aName] = newVal; + } else { + attrs[aName] = parseValue( + oldVal, + this.options.parseAttributeValue, + this.options.numberParseOptions + ); + } + } else if (this.options.allowBooleanAttributes) { + attrs[aName] = true; + } + } + } + if (!Object.keys(attrs).length) { + return; + } + if (this.options.attributesGroupName) { + const attrCollection = {}; + attrCollection[this.options.attributesGroupName] = attrs; + return attrCollection; + } + return attrs; + } + } + var parseXml = function(xmlData) { + xmlData = xmlData.replace(/\r\n?/g, "\n"); + const xmlObj = new xmlNode("!xml"); + let currentNode = xmlObj; + let textData = ""; + let jPath = ""; + for (let i = 0; i < xmlData.length; i++) { + const ch = xmlData[i]; + if (ch === "<") { + if (xmlData[i + 1] === "/") { + const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed."); + let tagName = xmlData.substring(i + 2, closeIndex).trim(); + if (this.options.removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + } + } + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + if (currentNode) { + textData = this.saveTextToParentTag(textData, currentNode, jPath); + } + const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1); + if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) { + throw new Error(`Unpaired tag can not be used as closing tag: `); + } + let propIndex = 0; + if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) { + propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1); + this.tagsNodeStack.pop(); + } else { + propIndex = jPath.lastIndexOf("."); + } + jPath = jPath.substring(0, propIndex); + currentNode = this.tagsNodeStack.pop(); + textData = ""; + i = closeIndex; + } else if (xmlData[i + 1] === "?") { + let tagData = readTagExp(xmlData, i, false, "?>"); + if (!tagData) throw new Error("Pi Tag is not closed."); + textData = this.saveTextToParentTag(textData, currentNode, jPath); + if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) { + } else { + const childNode = new xmlNode(tagData.tagName); + childNode.add(this.options.textNodeName, ""); + if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); + } + this.addChild(currentNode, childNode, jPath); + } + i = tagData.closeIndex + 1; + } else if (xmlData.substr(i + 1, 3) === "!--") { + const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed."); + if (this.options.commentPropName) { + const comment = xmlData.substring(i + 4, endIndex - 2); + textData = this.saveTextToParentTag(textData, currentNode, jPath); + currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]); + } + i = endIndex; + } else if (xmlData.substr(i + 1, 2) === "!D") { + const result = readDocType(xmlData, i); + this.docTypeEntities = result.entities; + i = result.i; + } else if (xmlData.substr(i + 1, 2) === "![") { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; + const tagExp = xmlData.substring(i + 9, closeIndex); + textData = this.saveTextToParentTag(textData, currentNode, jPath); + let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); + if (val2 == void 0) val2 = ""; + if (this.options.cdataPropName) { + currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]); + } else { + currentNode.add(this.options.textNodeName, val2); + } + i = closeIndex + 2; + } else { + let result = readTagExp(xmlData, i, this.options.removeNSPrefix); + let tagName = result.tagName; + const rawTagName = result.rawTagName; + let tagExp = result.tagExp; + let attrExpPresent = result.attrExpPresent; + let closeIndex = result.closeIndex; + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + if (currentNode && textData) { + if (currentNode.tagname !== "!xml") { + textData = this.saveTextToParentTag(textData, currentNode, jPath, false); + } + } + const lastTag = currentNode; + if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) { + currentNode = this.tagsNodeStack.pop(); + jPath = jPath.substring(0, jPath.lastIndexOf(".")); + } + if (tagName !== xmlObj.tagname) { + jPath += jPath ? "." + tagName : tagName; + } + if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { + let tagContent = ""; + if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + } else { + tagExp = tagExp.substr(0, tagExp.length - 1); + } + i = result.closeIndex; + } else if (this.options.unpairedTags.indexOf(tagName) !== -1) { + i = result.closeIndex; + } else { + const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); + if (!result2) throw new Error(`Unexpected end of ${rawTagName}`); + i = result2.i; + tagContent = result2.tagContent; + } + const childNode = new xmlNode(tagName); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + if (tagContent) { + tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); + } + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + childNode.add(this.options.textNodeName, tagContent); + this.addChild(currentNode, childNode, jPath); + } else { + if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + } else { + tagExp = tagExp.substr(0, tagExp.length - 1); + } + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + const childNode = new xmlNode(tagName); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath); + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + } else { + const childNode = new xmlNode(tagName); + this.tagsNodeStack.push(currentNode); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath); + currentNode = childNode; + } + textData = ""; + i = closeIndex; + } + } + } else { + textData += xmlData[i]; + } + } + return xmlObj.child; + }; + function addChild(currentNode, childNode, jPath) { + const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]); + if (result === false) { + } else if (typeof result === "string") { + childNode.tagname = result; + currentNode.addChild(childNode); + } else { + currentNode.addChild(childNode); + } + } + var replaceEntitiesValue = function(val2) { + if (this.options.processEntities) { + for (let entityName2 in this.docTypeEntities) { + const entity = this.docTypeEntities[entityName2]; + val2 = val2.replace(entity.regx, entity.val); + } + for (let entityName2 in this.lastEntities) { + const entity = this.lastEntities[entityName2]; + val2 = val2.replace(entity.regex, entity.val); + } + if (this.options.htmlEntities) { + for (let entityName2 in this.htmlEntities) { + const entity = this.htmlEntities[entityName2]; + val2 = val2.replace(entity.regex, entity.val); + } + } + val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val); + } + return val2; + }; + function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { + if (textData) { + if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0; + textData = this.parseTextData( + textData, + currentNode.tagname, + jPath, + false, + currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, + isLeafNode + ); + if (textData !== void 0 && textData !== "") + currentNode.add(this.options.textNodeName, textData); + textData = ""; + } + return textData; + } + function isItStopNode(stopNodes, jPath, currentTagName) { + const allNodesExp = "*." + currentTagName; + for (const stopNodePath in stopNodes) { + const stopNodeExp = stopNodes[stopNodePath]; + if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true; + } + return false; + } + function tagExpWithClosingIndex(xmlData, i, closingChar = ">") { + let attrBoundary; + let tagExp = ""; + for (let index = i; index < xmlData.length; index++) { + let ch = xmlData[index]; + if (attrBoundary) { + if (ch === attrBoundary) attrBoundary = ""; + } else if (ch === '"' || ch === "'") { + attrBoundary = ch; + } else if (ch === closingChar[0]) { + if (closingChar[1]) { + if (xmlData[index + 1] === closingChar[1]) { + return { + data: tagExp, + index + }; + } + } else { + return { + data: tagExp, + index + }; + } + } else if (ch === " ") { + ch = " "; + } + tagExp += ch; + } + } + function findClosingIndex(xmlData, str2, i, errMsg) { + const closingIndex = xmlData.indexOf(str2, i); + if (closingIndex === -1) { + throw new Error(errMsg); + } else { + return closingIndex + str2.length - 1; + } + } + function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") { + const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar); + if (!result) return; + let tagExp = result.data; + const closeIndex = result.index; + const separatorIndex = tagExp.search(/\s/); + let tagName = tagExp; + let attrExpPresent = true; + if (separatorIndex !== -1) { + tagName = tagExp.substring(0, separatorIndex); + tagExp = tagExp.substring(separatorIndex + 1).trimStart(); + } + const rawTagName = tagName; + if (removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + } + } + return { + tagName, + tagExp, + closeIndex, + attrExpPresent, + rawTagName + }; + } + function readStopNodeData(xmlData, tagName, i) { + const startIndex = i; + let openTagCount = 1; + for (; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + if (xmlData[i + 1] === "/") { + const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); + let closeTagName = xmlData.substring(i + 2, closeIndex).trim(); + if (closeTagName === tagName) { + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlData.substring(startIndex, i), + i: closeIndex + }; + } + } + i = closeIndex; + } else if (xmlData[i + 1] === "?") { + const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed."); + i = closeIndex; + } else if (xmlData.substr(i + 1, 3) === "!--") { + const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed."); + i = closeIndex; + } else if (xmlData.substr(i + 1, 2) === "![") { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; + i = closeIndex; + } else { + const tagData = readTagExp(xmlData, i, ">"); + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { + openTagCount++; + } + i = tagData.closeIndex; + } + } + } + } + } + function parseValue(val2, shouldParse, options) { + if (shouldParse && typeof val2 === "string") { + const newval = val2.trim(); + if (newval === "true") return true; + else if (newval === "false") return false; + else return toNumber(val2, options); + } else { + if (util.isExist(val2)) { + return val2; + } else { + return ""; + } + } + } + module2.exports = OrderedObjParser; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/node2json.js +var require_node2json = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports2) { + "use strict"; + function prettify(node, options) { + return compress(node, options); + } + function compress(arr, options, jPath) { + let text; + const compressedObj = {}; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const property = propName(tagObj); + let newJpath = ""; + if (jPath === void 0) newJpath = property; + else newJpath = jPath + "." + property; + if (property === options.textNodeName) { + if (text === void 0) text = tagObj[property]; + else text += "" + tagObj[property]; + } else if (property === void 0) { + continue; + } else if (tagObj[property]) { + let val2 = compress(tagObj[property], options, newJpath); + const isLeaf = isLeafTag(val2, options); + if (tagObj[":@"]) { + assignAttributes(val2, tagObj[":@"], newJpath, options); + } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) { + val2 = val2[options.textNodeName]; + } else if (Object.keys(val2).length === 0) { + if (options.alwaysCreateTextNode) val2[options.textNodeName] = ""; + else val2 = ""; + } + if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) { + if (!Array.isArray(compressedObj[property])) { + compressedObj[property] = [compressedObj[property]]; + } + compressedObj[property].push(val2); + } else { + if (options.isArray(property, newJpath, isLeaf)) { + compressedObj[property] = [val2]; + } else { + compressedObj[property] = val2; + } + } + } + } + if (typeof text === "string") { + if (text.length > 0) compressedObj[options.textNodeName] = text; + } else if (text !== void 0) compressedObj[options.textNodeName] = text; + return compressedObj; + } + function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key !== ":@") return key; + } + } + function assignAttributes(obj, attrMap, jpath, options) { + if (attrMap) { + const keys = Object.keys(attrMap); + const len = keys.length; + for (let i = 0; i < len; i++) { + const atrrName = keys[i]; + if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { + obj[atrrName] = [attrMap[atrrName]]; + } else { + obj[atrrName] = attrMap[atrrName]; + } + } + } + } + function isLeafTag(obj, options) { + const { textNodeName } = options; + const propCount = Object.keys(obj).length; + if (propCount === 0) { + return true; + } + if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) { + return true; + } + return false; + } + exports2.prettify = prettify; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/XMLParser.js +var require_XMLParser = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module2) { + var { buildOptions } = require_OptionsBuilder(); + var OrderedObjParser = require_OrderedObjParser(); + var { prettify } = require_node2json(); + var validator = require_validator(); + var XMLParser = class { + constructor(options) { + this.externalEntities = {}; + this.options = buildOptions(options); + } + /** + * Parse XML dats to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData, validationOption) { + if (typeof xmlData === "string") { + } else if (xmlData.toString) { + xmlData = xmlData.toString(); + } else { + throw new Error("XML data is accepted in String or Bytes[] form."); + } + if (validationOption) { + if (validationOption === true) validationOption = {}; + const result = validator.validate(xmlData, validationOption); + if (result !== true) { + throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`); + } + } + const orderedObjParser = new OrderedObjParser(this.options); + orderedObjParser.addExternalEntities(this.externalEntities); + const orderedResult = orderedObjParser.parseXml(xmlData); + if (this.options.preserveOrder || orderedResult === void 0) return orderedResult; + else return prettify(orderedResult, this.options); + } + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value) { + if (value.indexOf("&") !== -1) { + throw new Error("Entity value can't have '&'"); + } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '"); + } else if (value === "&") { + throw new Error("An entity with value '&' is not permitted"); + } else { + this.externalEntities[key] = value; + } + } + }; + module2.exports = XMLParser; + } +}); + +// node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js +var require_orderedJs2Xml = __commonJS({ + "node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module2) { + var EOL = "\n"; + function toXml(jArray, options) { + let indentation = ""; + if (options.format && options.indentBy.length > 0) { + indentation = EOL; + } + return arrToStr(jArray, options, "", indentation); + } + function arrToStr(arr, options, jPath, indentation) { + let xmlStr = ""; + let isPreviousElementTag = false; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const tagName = propName(tagObj); + if (tagName === void 0) continue; + let newJPath = ""; + if (jPath.length === 0) newJPath = tagName; + else newJPath = `${jPath}.${tagName}`; + if (tagName === options.textNodeName) { + let tagText = tagObj[tagName]; + if (!isStopNode(newJPath, options)) { + tagText = options.tagValueProcessor(tagName, tagText); + tagText = replaceEntitiesValue(tagText, options); + } + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += tagText; + isPreviousElementTag = false; + continue; + } else if (tagName === options.cdataPropName) { + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += ``; + isPreviousElementTag = false; + continue; + } else if (tagName === options.commentPropName) { + xmlStr += indentation + ``; + isPreviousElementTag = true; + continue; + } else if (tagName[0] === "?") { + const attStr2 = attr_to_str(tagObj[":@"], options); + const tempInd = tagName === "?xml" ? "" : indentation; + let piTextNodeName = tagObj[tagName][0][options.textNodeName]; + piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; + xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`; + isPreviousElementTag = true; + continue; + } + let newIdentation = indentation; + if (newIdentation !== "") { + newIdentation += options.indentBy; + } + const attStr = attr_to_str(tagObj[":@"], options); + const tagStart = indentation + `<${tagName}${attStr}`; + const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); + if (options.unpairedTags.indexOf(tagName) !== -1) { + if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; + else xmlStr += tagStart + "/>"; + } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { + xmlStr += tagStart + "/>"; + } else if (tagValue && tagValue.endsWith(">")) { + xmlStr += tagStart + `>${tagValue}${indentation}`; + } else { + xmlStr += tagStart + ">"; + if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; + } + isPreviousElementTag = true; + } + return xmlStr; + } + function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (!obj.hasOwnProperty(key)) continue; + if (key !== ":@") return key; + } + } + function attr_to_str(attrMap, options) { + let attrStr = ""; + if (attrMap && !options.ignoreAttributes) { + for (let attr in attrMap) { + if (!attrMap.hasOwnProperty(attr)) continue; + let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); + attrVal = replaceEntitiesValue(attrVal, options); + if (attrVal === true && options.suppressBooleanAttributes) { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + } else { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + } + } + } + return attrStr; + } + function isStopNode(jPath, options) { + jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); + let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); + for (let index in options.stopNodes) { + if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; + } + return false; + } + function replaceEntitiesValue(textValue, options) { + if (textValue && textValue.length > 0 && options.processEntities) { + for (let i = 0; i < options.entities.length; i++) { + const entity = options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } + } + return textValue; + } + module2.exports = toXml; + } +}); + +// node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js +var require_json2xml = __commonJS({ + "node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports2, module2) { + "use strict"; + var buildFromOrderedJs = require_orderedJs2Xml(); + var getIgnoreAttributesFn = require_ignoreAttributes(); + var defaultOptions = { + attributeNamePrefix: "@_", + attributesGroupName: false, + textNodeName: "#text", + ignoreAttributes: true, + cdataPropName: false, + format: false, + indentBy: " ", + suppressEmptyNode: false, + suppressUnpairedNode: true, + suppressBooleanAttributes: true, + tagValueProcessor: function(key, a) { + return a; + }, + attributeValueProcessor: function(attrName, a) { + return a; + }, + preserveOrder: false, + commentPropName: false, + unpairedTags: [], + entities: [ + { regex: new RegExp("&", "g"), val: "&" }, + //it must be on top + { regex: new RegExp(">", "g"), val: ">" }, + { regex: new RegExp("<", "g"), val: "<" }, + { regex: new RegExp("'", "g"), val: "'" }, + { regex: new RegExp('"', "g"), val: """ } + ], + processEntities: true, + stopNodes: [], + // transformTagName: false, + // transformAttributeName: false, + oneListGroup: false + }; + function Builder(options) { + this.options = Object.assign({}, defaultOptions, options); + if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { + this.isAttribute = function() { + return false; + }; + } else { + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); + this.attrPrefixLen = this.options.attributeNamePrefix.length; + this.isAttribute = isAttribute; + } + this.processTextOrObjNode = processTextOrObjNode; + if (this.options.format) { + this.indentate = indentate; + this.tagEndChar = ">\n"; + this.newLine = "\n"; + } else { + this.indentate = function() { + return ""; + }; + this.tagEndChar = ">"; + this.newLine = ""; + } + } + Builder.prototype.build = function(jObj) { + if (this.options.preserveOrder) { + return buildFromOrderedJs(jObj, this.options); + } else { + if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) { + jObj = { + [this.options.arrayNodeName]: jObj + }; + } + return this.j2x(jObj, 0, []).val; + } + }; + Builder.prototype.j2x = function(jObj, level, ajPath) { + let attrStr = ""; + let val2 = ""; + const jPath = ajPath.join("."); + for (let key in jObj) { + if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue; + if (typeof jObj[key] === "undefined") { + if (this.isAttribute(key)) { + val2 += ""; + } + } else if (jObj[key] === null) { + if (this.isAttribute(key)) { + val2 += ""; + } else if (key[0] === "?") { + val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; + } else { + val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; + } + } else if (jObj[key] instanceof Date) { + val2 += this.buildTextValNode(jObj[key], key, "", level); + } else if (typeof jObj[key] !== "object") { + const attr = this.isAttribute(key); + if (attr && !this.ignoreAttributesFn(attr, jPath)) { + attrStr += this.buildAttrPairStr(attr, "" + jObj[key]); + } else if (!attr) { + if (key === this.options.textNodeName) { + let newval = this.options.tagValueProcessor(key, "" + jObj[key]); + val2 += this.replaceEntitiesValue(newval); + } else { + val2 += this.buildTextValNode(jObj[key], key, "", level); + } + } + } else if (Array.isArray(jObj[key])) { + const arrLen = jObj[key].length; + let listTagVal = ""; + let listTagAttr = ""; + for (let j = 0; j < arrLen; j++) { + const item = jObj[key][j]; + if (typeof item === "undefined") { + } else if (item === null) { + if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; + else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; + } else if (typeof item === "object") { + if (this.options.oneListGroup) { + const result = this.j2x(item, level + 1, ajPath.concat(key)); + listTagVal += result.val; + if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { + listTagAttr += result.attrStr; + } + } else { + listTagVal += this.processTextOrObjNode(item, key, level, ajPath); + } + } else { + if (this.options.oneListGroup) { + let textValue = this.options.tagValueProcessor(key, item); + textValue = this.replaceEntitiesValue(textValue); + listTagVal += textValue; + } else { + listTagVal += this.buildTextValNode(item, key, "", level); + } + } + } + if (this.options.oneListGroup) { + listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); + } + val2 += listTagVal; + } else { + if (this.options.attributesGroupName && key === this.options.attributesGroupName) { + const Ks = Object.keys(jObj[key]); + const L = Ks.length; + for (let j = 0; j < L; j++) { + attrStr += this.buildAttrPairStr(Ks[j], "" + jObj[key][Ks[j]]); + } + } else { + val2 += this.processTextOrObjNode(jObj[key], key, level, ajPath); + } + } + } + return { attrStr, val: val2 }; + }; + Builder.prototype.buildAttrPairStr = function(attrName, val2) { + val2 = this.options.attributeValueProcessor(attrName, "" + val2); + val2 = this.replaceEntitiesValue(val2); + if (this.options.suppressBooleanAttributes && val2 === "true") { + return " " + attrName; + } else return " " + attrName + '="' + val2 + '"'; + }; + function processTextOrObjNode(object, key, level, ajPath) { + const result = this.j2x(object, level + 1, ajPath.concat(key)); + if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) { + return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); + } else { + return this.buildObjectNode(result.val, key, result.attrStr, level); + } + } + Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) { + if (val2 === "") { + if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; + else { + return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; + } + } else { + let tagEndExp = "" + val2 + tagEndExp; + } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { + return this.indentate(level) + `` + this.newLine; + } else { + return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp; + } + } + }; + Builder.prototype.closeTag = function(key) { + let closeTag = ""; + if (this.options.unpairedTags.indexOf(key) !== -1) { + if (!this.options.suppressUnpairedNode) closeTag = "/"; + } else if (this.options.suppressEmptyNode) { + closeTag = "/"; + } else { + closeTag = `>` + this.newLine; + } else if (this.options.commentPropName !== false && key === this.options.commentPropName) { + return this.indentate(level) + `` + this.newLine; + } else if (key[0] === "?") { + return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; + } else { + let textValue = this.options.tagValueProcessor(key, val2); + textValue = this.replaceEntitiesValue(textValue); + if (textValue === "") { + return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; + } else { + return this.indentate(level) + "<" + key + attrStr + ">" + textValue + " 0 && this.options.processEntities) { + for (let i = 0; i < this.options.entities.length; i++) { + const entity = this.options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } + } + return textValue; + }; + function indentate(level) { + return this.options.indentBy.repeat(level); + } + function isAttribute(name) { + if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) { + return name.substr(this.attrPrefixLen); + } else { + return false; + } + } + module2.exports = Builder; + } +}); + +// node_modules/fast-xml-parser/src/fxp.js +var require_fxp = __commonJS({ + "node_modules/fast-xml-parser/src/fxp.js"(exports2, module2) { + "use strict"; + var validator = require_validator(); + var XMLParser = require_XMLParser(); + var XMLBuilder = require_json2xml(); + module2.exports = { + XMLParser, + XMLValidator: validator, + XMLBuilder + }; + } +}); + +// node_modules/@azure/core-xml/dist/commonjs/xml.common.js +var require_xml_common = __commonJS({ + "node_modules/@azure/core-xml/dist/commonjs/xml.common.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.XML_CHARKEY = exports2.XML_ATTRKEY = void 0; + exports2.XML_ATTRKEY = "$"; + exports2.XML_CHARKEY = "_"; + } +}); + +// node_modules/@azure/core-xml/dist/commonjs/xml.js +var require_xml = __commonJS({ + "node_modules/@azure/core-xml/dist/commonjs/xml.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stringifyXML = stringifyXML; + exports2.parseXML = parseXML; + var fast_xml_parser_1 = require_fxp(); + var xml_common_js_1 = require_xml_common(); + function getCommonOptions(options) { + var _a; + return { + attributesGroupName: xml_common_js_1.XML_ATTRKEY, + textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_js_1.XML_CHARKEY, + ignoreAttributes: false, + suppressBooleanAttributes: false + }; + } + function getSerializerOptions(options = {}) { + var _a, _b; + return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" }); + } + function getParserOptions(options = {}) { + return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true }); + } + function stringifyXML(obj, opts = {}) { + const parserOptions = getSerializerOptions(opts); + const j2x = new fast_xml_parser_1.XMLBuilder(parserOptions); + const node = { [parserOptions.rootNodeName]: obj }; + const xmlData = j2x.build(node); + return `${xmlData}`.replace(/\n/g, ""); + } + async function parseXML(str2, opts = {}) { + if (!str2) { + throw new Error("Document is empty"); + } + const validation = fast_xml_parser_1.XMLValidator.validate(str2); + if (validation !== true) { + throw validation; + } + const parser = new fast_xml_parser_1.XMLParser(getParserOptions(opts)); + const parsedXml = parser.parse(str2); + if (parsedXml["?xml"]) { + delete parsedXml["?xml"]; + } + if (!opts.includeRoot) { + for (const key of Object.keys(parsedXml)) { + const value = parsedXml[key]; + return typeof value === "object" ? Object.assign({}, value) : value; + } + } + return parsedXml; + } + } +}); + +// node_modules/@azure/core-xml/dist/commonjs/index.js +var require_commonjs9 = __commonJS({ + "node_modules/@azure/core-xml/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.XML_CHARKEY = exports2.XML_ATTRKEY = exports2.parseXML = exports2.stringifyXML = void 0; + var xml_js_1 = require_xml(); + Object.defineProperty(exports2, "stringifyXML", { enumerable: true, get: function() { + return xml_js_1.stringifyXML; + } }); + Object.defineProperty(exports2, "parseXML", { enumerable: true, get: function() { + return xml_js_1.parseXML; + } }); + var xml_common_js_1 = require_xml_common(); + Object.defineProperty(exports2, "XML_ATTRKEY", { enumerable: true, get: function() { + return xml_common_js_1.XML_ATTRKEY; + } }); + Object.defineProperty(exports2, "XML_CHARKEY", { enumerable: true, get: function() { + return xml_common_js_1.XML_CHARKEY; + } }); + } +}); + +// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError3 = __commonJS({ + "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError; + } +}); + +// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs10 = __commonJS({ + "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError3(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/abort-controller/dist/index.js +var require_dist5 = __commonJS({ + "node_modules/@azure/abort-controller/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var listenersMap = /* @__PURE__ */ new WeakMap(); + var abortedMap = /* @__PURE__ */ new WeakMap(); + var AbortSignal2 = class _AbortSignal { + constructor() { + this.onabort = null; + 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(); + } + /** + * Added new "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be added + */ + addEventListener(_type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + 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 + */ + removeEventListener(_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); + if (index > -1) { + listeners.splice(index, 1); + } + } + /** + * Dispatches a synthetic event to the AbortSignal. + */ + dispatchEvent(_event) { + throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); + } + }; + function abortSignal(signal) { + if (signal.aborted) { + return; + } + if (signal.onabort) { + signal.onabort.call(signal); + } + const listeners = listenersMap.get(signal); + if (listeners) { + listeners.slice().forEach((listener) => { + listener.call(signal, { type: "abort" }); + }); + } + abortedMap.set(signal, true); + } + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + var AbortController2 = class { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + constructor(parentSignals) { + this._signal = new AbortSignal2(); + if (!parentSignals) { + return; + } + if (!Array.isArray(parentSignals)) { + parentSignals = arguments; + } + for (const parentSignal of parentSignals) { + if (parentSignal.aborted) { + this.abort(); + } else { + parentSignal.addEventListener("abort", () => { + 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; + } + /** + * Signal that any operations passed this controller's associated abort signal + * to cancel any remaining work and throw an `AbortError`. + */ + 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. + */ + static timeout(ms) { + const signal = new AbortSignal2(); + const timer = setTimeout(abortSignal, ms, signal); + if (typeof timer.unref === "function") { + timer.unref(); + } + return signal; + } + }; + exports2.AbortController = AbortController2; + exports2.AbortError = AbortError; + exports2.AbortSignal = AbortSignal2; + } +}); + +// node_modules/@azure/core-lro/dist/index.js +var require_dist6 = __commonJS({ + "node_modules/@azure/core-lro/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var logger$1 = require_dist(); + var abortController = require_dist5(); + var coreUtil = require_commonjs2(); + var logger = logger$1.createClientLogger("core-lro"); + var POLL_INTERVAL_IN_MS = 2e3; + var terminalStates = ["succeeded", "canceled", "failed"]; + 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: isOperationError2 } = inputs; + return (error2) => { + if (isOperationError2(error2)) { + stateProxy.setError(state, error2); + stateProxy.setFailed(state); + } + throw error2; + }; + } + function appendReadableErrorMessage(currentMessage, innerMessage) { + let message = currentMessage; + if (message.slice(-1) !== ".") { + message = message + "."; + } + return message + " " + innerMessage; + } + function simplifyError(err) { + let message = err.message; + let code = err.code; + let curErr = err; + while (curErr.innererror) { + curErr = curErr.innererror; + code = curErr.code; + message = appendReadableErrorMessage(message, curErr.message); + } + return { + code, + message + }; + } + function processOperationStatus(result) { + const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result; + switch (status) { + case "succeeded": { + stateProxy.setSucceeded(state); + break; + } + case "failed": { + const err = getError === null || getError === void 0 ? void 0 : getError(response); + let postfix = ""; + if (err) { + const { code, message } = simplifyError(err); + postfix = `. ${code}. ${message}`; + } + const errStr = `The long-running operation has failed${postfix}`; + stateProxy.setError(state, new Error(errStr)); + stateProxy.setFailed(state); + logger.warning(errStr); + break; + } + case "canceled": { + stateProxy.setCanceled(state); + break; + } + } + if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || isDone === void 0 && ["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; + } + async function initOperation(inputs) { + const { init, stateProxy, processResult, getOperationStatus: getOperationStatus2, 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 = getOperationStatus2({ response, state, operationLocation }); + processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult }); + return state; + } + async function pollOperationHelper(inputs) { + const { poll, state, stateProxy, operationLocation, getOperationStatus: getOperationStatus2, getResourceLocation: getResourceLocation2, isOperationError: isOperationError2, options } = inputs; + const response = await poll(operationLocation, options).catch(setStateError({ + state, + stateProxy, + isOperationError: isOperationError2 + })); + const status = getOperationStatus2(response, state); + logger.verbose(`LRO: Status: + Polling from: ${state.config.operationLocation} + Operation status: ${status} + Polling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); + if (status === "succeeded") { + const resourceLocation = getResourceLocation2(response, state); + if (resourceLocation !== void 0) { + return { + response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError: isOperationError2 })), + status + }; + } + } + return { response, status }; + } + async function pollOperation(inputs) { + const { poll, state, stateProxy, options, getOperationStatus: getOperationStatus2, getResourceLocation: getResourceLocation2, getOperationLocation: getOperationLocation2, isOperationError: isOperationError2, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult } = inputs; + const { operationLocation } = state.config; + if (operationLocation !== void 0) { + const { response, status } = await pollOperationHelper({ + poll, + getOperationStatus: getOperationStatus2, + state, + stateProxy, + operationLocation, + getResourceLocation: getResourceLocation2, + isOperationError: isOperationError2, + options + }); + processOperationStatus({ + status, + response, + state, + stateProxy, + isDone, + processResult, + getError, + setErrorAsResult + }); + if (!terminalStates.includes(status)) { + const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); + if (intervalInMs) + setDelay(intervalInMs); + const location = getOperationLocation2 === null || getOperationLocation2 === void 0 ? void 0 : getOperationLocation2(response, state); + if (location !== void 0) { + 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); + } + } + 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 void 0; + } + default: { + switch (resourceLocationConfig) { + case "azure-async-operation": { + return void 0; + } + 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 !== void 0) { + return { + mode: "OperationLocation", + operationLocation: pollingUrl, + resourceLocation: findResourceLocation({ + requestMethod: normalizedRequestMethod, + location, + requestPath, + resourceLocationConfig + }) + }; + } else if (location !== void 0) { + return { + mode: "ResourceLocation", + operationLocation: location + }; + } else if (normalizedRequestMethod === "PUT" && requestPath) { + return { + mode: "Body", + operationLocation: requestPath + }; + } else { + return void 0; + } + } + function transformStatus(inputs) { + const { status, statusCode } = inputs; + if (typeof status !== "string" && status !== void 0) { + 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 void 0: + 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 !== void 0) { + const retryAfterInSeconds = parseInt(retryAfter); + return isNaN(retryAfterInSeconds) ? calculatePollingIntervalFromDate(new Date(retryAfter)) : retryAfterInSeconds * 1e3; + } + return void 0; + } + function getErrorFromResponse(response) { + const error2 = response.flatResponse.error; + if (!error2) { + logger.warning(`The long-running operation failed but there is no error property in the response's body`); + return; + } + if (!error2.code || !error2.message) { + logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`); + return; + } + return error2; + } + function calculatePollingIntervalFromDate(retryAfterDate) { + const timeNow = Math.floor((/* @__PURE__ */ new Date()).getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return void 0; + } + 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 void 0: + return toOperationStatus(response.rawResponse.statusCode); + case "Body": + return getOperationStatus(response, state); + default: + return "running"; + } + } + const status = helper(); + return status === "running" && operationLocation === void 0 ? "succeeded" : status; + } + 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 void 0; + } + } + } + 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 !== void 0) { + state.config.resourceLocation = resourceLocation; + } + } + return state.config.resourceLocation; + } + function isOperationError(e) { + return e.name === "RestError"; + } + 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, + getError: getErrorFromResponse, + 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 + }); + } + var 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, error2) => state.error = error2, + 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" + }); + function buildCreatePoller(inputs) { + const { getOperationLocation: getOperationLocation2, getStatusFromInitialResponse: getStatusFromInitialResponse2, getStatusFromPollResponse, isOperationError: isOperationError2, getResourceLocation: getResourceLocation2, getPollingInterval, getError, 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 ? /* @__PURE__ */ (() => { + let called = false; + return (operationLocation, isUpdated) => { + if (isUpdated) + withOperationLocationCallback(operationLocation); + else if (!called) + withOperationLocationCallback(operationLocation); + called = true; + }; + })() : void 0; + const state = restoreFrom ? deserializeState(restoreFrom) : await initOperation({ + init, + stateProxy, + processResult, + getOperationStatus: getStatusFromInitialResponse2, + withOperationLocation, + setErrorAsResult: !resolveOnUnsuccessful + }); + let resultPromise; + const abortController$1 = new abortController.AbortController(); + const handlers = /* @__PURE__ */ 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 === void 0, + 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 = void 0; + }), + 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: getOperationLocation2, + isOperationError: isOperationError2, + withOperationLocation, + getPollingInterval, + getOperationStatus: getStatusFromPollResponse, + getResourceLocation: getResourceLocation2, + processResult, + getError, + 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; + }; + } + 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, + getError: getErrorFromResponse, + 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 + }); + } + var createStateProxy = () => ({ + initState: (config) => ({ config, isStarted: true }), + setCanceled: (state) => state.isCancelled = true, + setError: (state, error2) => state.error = error2, + setResult: (state, result) => state.result = result, + setRunning: (state) => state.isStarted = true, + setSucceeded: (state) => state.isCompleted = true, + setFailed: () => { + }, + 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) + }); + var GenericPollOperation = class { + 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 === void 0) { + await pollHttpOperation({ + lro: this.lro, + state: this.state, + stateProxy, + processResult: this.processResult, + updateState: updateState ? (state, { rawResponse }) => updateState(state, rawResponse) : void 0, + isDone: isDone ? ({ flatResponse }, state) => isDone(flatResponse, state) : void 0, + 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 + }); + } + }; + var PollerStoppedError = class _PollerStoppedError extends Error { + constructor(message) { + super(message); + this.name = "PollerStoppedError"; + Object.setPrototypeOf(this, _PollerStoppedError.prototype); + } + }; + var PollerCancelledError = class _PollerCancelledError extends Error { + constructor(message) { + super(message); + this.name = "PollerCancelledError"; + Object.setPrototypeOf(this, _PollerCancelledError.prototype); + } + }; + var Poller = class { + /** + * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`. + * + * When writing an implementation of a Poller, this implementation needs to deal with the initialization + * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's + * operation has already been defined, at least its basic properties. The code below shows how to approach + * the definition of the constructor of a new custom poller. + * + * ```ts + * export class MyPoller extends Poller { + * constructor({ + * // Anything you might need outside of the basics + * }) { + * let state: MyOperationState = { + * privateProperty: private, + * publicProperty: public, + * }; + * + * const operation = { + * state, + * update, + * cancel, + * toString + * } + * + * // Sending the operation to the parent's constructor. + * super(operation); + * + * // You can assign more local properties here. + * } + * } + * ``` + * + * Inside of this constructor, a new promise is created. This will be used to + * tell the user when the poller finishes (see `pollUntilDone()`). The promise's + * resolve and reject methods are also used internally to control when to resolve + * or reject anyone waiting for the poller to finish. + * + * The constructor of a custom implementation of a poller is where any serialized version of + * a previous poller's operation should be deserialized into the operation sent to the + * base constructor. For example: + * + * ```ts + * export class MyPoller extends Poller { + * constructor( + * baseOperation: string | undefined + * ) { + * let state: MyOperationState = {}; + * if (baseOperation) { + * state = { + * ...JSON.parse(baseOperation).state, + * ...state + * }; + * } + * const operation = { + * state, + * // ... + * } + * super(operation); + * } + * } + * ``` + * + * @param operation - Must contain the basic properties of `PollOperation`. + */ + constructor(operation) { + this.resolveOnUnsuccessful = false; + this.stopped = true; + this.pollProgressCallbacks = []; + this.operation = operation; + this.promise = new Promise((resolve2, reject) => { + this.resolve = resolve2; + this.reject = reject; + }); + this.promise.catch(() => { + }); + } + /** + * Starts a loop that will break only if the poller is done + * or if the poller is stopped. + */ + async startPolling(pollOptions = {}) { + if (this.stopped) { + this.stopped = false; + } + while (!this.isStopped() && !this.isDone()) { + await this.poll(pollOptions); + await this.delay(); + } + } + /** + * pollOnce does one polling, by calling to the update method of the underlying + * poll operation to make any relevant change effective. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * @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) + }); + } + this.processUpdatedState(); + } + /** + * fireProgress calls the functions passed in via onProgress the method of the poller. + * + * It loops over all of the callbacks received from onProgress, and executes them, sending them + * the current operation state. + * + * @param state - The current operation state. + */ + fireProgress(state) { + for (const callback of this.pollProgressCallbacks) { + callback(state); + } + } + /** + * Invokes the underlying operation's cancel method. + */ + async cancelOnce(options = {}) { + this.operation = await this.operation.cancel(options); + } + /** + * Returns a promise that will resolve once a single polling request finishes. + * It does this by calling the update method of the Poller's operation. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * @param options - Optional properties passed to the operation's update method. + */ + poll(options = {}) { + if (!this.pollOncePromise) { + this.pollOncePromise = this.pollOnce(options); + const clearPollOncePromise = () => { + this.pollOncePromise = void 0; + }; + this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject); + } + 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 error2 = new PollerCancelledError("Operation was canceled"); + this.reject(error2); + throw error2; + } + } + if (this.isDone() && this.resolve) { + this.resolve(this.getResult()); + } + } + /** + * Returns a promise that will resolve once the underlying operation is completed. + */ + async pollUntilDone(pollOptions = {}) { + if (this.stopped) { + this.startPolling(pollOptions).catch(this.reject); + } + this.processUpdatedState(); + return this.promise; + } + /** + * Invokes the provided callback after each polling is completed, + * sending the current state of the poller's operation. + * + * It returns a method that can be used to stop receiving updates on the given callback function. + */ + onProgress(callback) { + this.pollProgressCallbacks.push(callback); + return () => { + this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback); + }; + } + /** + * Returns true if the poller has finished polling. + */ + isDone() { + const state = this.operation.state; + return Boolean(state.isCompleted || state.isCancelled || state.error); + } + /** + * Stops the poller from continuing to poll. + */ + stopPolling() { + if (!this.stopped) { + this.stopped = true; + if (this.reject) { + this.reject(new PollerStoppedError("This poller is already stopped")); + } + } + } + /** + * Returns true if the poller is stopped. + */ + isStopped() { + return this.stopped; + } + /** + * Attempts to cancel the underlying operation. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * If it's called again before it finishes, it will throw an error. + * + * @param options - Optional properties passed to the operation's update method. + */ + cancelOperation(options = {}) { + if (!this.cancelPromise) { + this.cancelPromise = this.cancelOnce(options); + } else if (options.abortSignal) { + throw new Error("A cancel request is currently pending"); + } + return this.cancelPromise; + } + /** + * Returns the state of the operation. + * + * Even though TState will be the same type inside any of the methods of any extension of the Poller class, + * implementations of the pollers can customize what's shared with the public by writing their own + * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller + * and a public type representing a safe to share subset of the properties of the internal state. + * Their definition of getOperationState can then return their public type. + * + * Example: + * + * ```ts + * // Let's say we have our poller's operation state defined as: + * interface MyOperationState extends PollOperationState { + * privateProperty?: string; + * publicProperty?: string; + * } + * + * // To allow us to have a true separation of public and private state, we have to define another interface: + * interface PublicState extends PollOperationState { + * publicProperty?: string; + * } + * + * // Then, we define our Poller as follows: + * export class MyPoller extends Poller { + * // ... More content is needed here ... + * + * public getOperationState(): PublicState { + * const state: PublicState = this.operation.state; + * return { + * // Properties from PollOperationState + * isStarted: state.isStarted, + * isCompleted: state.isCompleted, + * isCancelled: state.isCancelled, + * error: state.error, + * result: state.result, + * + * // The only other property needed by PublicState. + * publicProperty: state.publicProperty + * } + * } + * } + * ``` + * + * You can see this in the tests of this repository, go to the file: + * `../test/utils/testPoller.ts` + * and look for the getOperationState implementation. + */ + getOperationState() { + return this.operation.state; + } + /** + * Returns the result value of the operation, + * regardless of the state of the poller. + * It can return undefined or an incomplete form of the final TResult value + * depending on the implementation. + */ + getResult() { + const state = this.operation.state; + return state.result; + } + /** + * Returns a serialized version of the poller's operation + * by invoking the operation's toString method. + */ + toString() { + return this.operation.toString(); + } + }; + var LroEngine = class extends Poller { + constructor(lro, 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, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone); + super(operation); + this.resolveOnUnsuccessful = resolveOnUnsuccessful; + this.config = { intervalInMs }; + operation.setPollerConfig(this.config); + } + /** + * The method used by the poller to wait before attempting to update its operation. + */ + delay() { + return new Promise((resolve2) => setTimeout(() => resolve2(), this.config.intervalInMs)); + } + }; + exports2.LroEngine = LroEngine; + exports2.Poller = Poller; + exports2.PollerCancelledError = PollerCancelledError; + exports2.PollerStoppedError = PollerStoppedError; + exports2.createHttpPoller = createHttpPoller; + } +}); + +// node_modules/@azure/storage-blob/dist/index.js +var require_dist7 = __commonJS({ + "node_modules/@azure/storage-blob/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var coreRestPipeline = require_commonjs5(); + var tslib = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); + var coreAuth = require_commonjs6(); + var coreUtil = require_commonjs2(); + var coreHttpCompat = require_commonjs8(); + var coreClient = require_commonjs7(); + var coreXml = require_commonjs9(); + var logger$1 = require_dist(); + var abortController = require_commonjs10(); + var crypto = require("crypto"); + var coreTracing = require_commonjs4(); + var stream = require("stream"); + var coreLro = require_dist6(); + var events = require("events"); + var fs = require("fs"); + var util = require("util"); + var buffer = require("buffer"); + function _interopNamespaceDefault(e) { + var n = /* @__PURE__ */ Object.create(null); + if (e) { + Object.keys(e).forEach(function(k) { + if (k !== "default") { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function() { + return e[k]; + } + }); + } + }); + } + n.default = e; + return Object.freeze(n); + } + var coreHttpCompat__namespace = /* @__PURE__ */ _interopNamespaceDefault(coreHttpCompat); + var coreClient__namespace = /* @__PURE__ */ _interopNamespaceDefault(coreClient); + var fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs); + var util__namespace = /* @__PURE__ */ _interopNamespaceDefault(util); + var logger = logger$1.createClientLogger("storage-blob"); + var BaseRequestPolicy = class { + /** + * The main method to implement that manipulates a request/response. + */ + constructor(_nextPolicy, _options) { + this._nextPolicy = _nextPolicy; + this._options = _options; + } + /** + * Get whether or not a log with the provided log level should be logged. + * @param logLevel - The log level of the log that will be logged. + * @returns Whether or not a log with the provided log level should be logged. + */ + shouldLog(logLevel) { + return this._options.shouldLog(logLevel); + } + /** + * Attempt to log the provided message to the provided logger. If no logger was provided or if + * the log level does not meat the logger's threshold, then nothing will be logged. + * @param logLevel - The log level of this log. + * @param message - The message of this log. + */ + log(logLevel, message) { + this._options.log(logLevel, message); + } + }; + var SDK_VERSION = "12.25.0"; + var SERVICE_VERSION = "2024-11-04"; + var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; + var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4e3 * 1024 * 1024; + var BLOCK_BLOB_MAX_BLOCKS = 5e4; + var DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; + var DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; + var DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; + var REQUEST_TIMEOUT = 100 * 1e3; + var StorageOAuthScopes = "https://storage.azure.com/.default"; + var URLConstants = { + Parameters: { + FORCE_BROWSER_NO_CACHE: "_", + SIGNATURE: "sig", + SNAPSHOT: "snapshot", + VERSIONID: "versionid", + TIMEOUT: "timeout" + } + }; + var HTTPURLConnection = { + HTTP_ACCEPTED: 202, + HTTP_CONFLICT: 409, + HTTP_NOT_FOUND: 404, + HTTP_PRECON_FAILED: 412, + HTTP_RANGE_NOT_SATISFIABLE: 416 + }; + var HeaderConstants = { + AUTHORIZATION: "Authorization", + AUTHORIZATION_SCHEME: "Bearer", + CONTENT_ENCODING: "Content-Encoding", + CONTENT_ID: "Content-ID", + CONTENT_LANGUAGE: "Content-Language", + CONTENT_LENGTH: "Content-Length", + CONTENT_MD5: "Content-Md5", + CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", + CONTENT_TYPE: "Content-Type", + COOKIE: "Cookie", + DATE: "date", + IF_MATCH: "if-match", + IF_MODIFIED_SINCE: "if-modified-since", + IF_NONE_MATCH: "if-none-match", + IF_UNMODIFIED_SINCE: "if-unmodified-since", + PREFIX_FOR_STORAGE: "x-ms-", + RANGE: "Range", + USER_AGENT: "User-Agent", + X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", + X_MS_COPY_SOURCE: "x-ms-copy-source", + X_MS_DATE: "x-ms-date", + X_MS_ERROR_CODE: "x-ms-error-code", + X_MS_VERSION: "x-ms-version", + X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code" + }; + var ETagNone = ""; + var ETagAny = "*"; + var SIZE_1_MB = 1 * 1024 * 1024; + var BATCH_MAX_REQUEST = 256; + var BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; + var HTTP_LINE_ENDING = "\r\n"; + var HTTP_VERSION_1_1 = "HTTP/1.1"; + var EncryptionAlgorithmAES25 = "AES256"; + var DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; + var StorageBlobLoggingAllowedHeaderNames = [ + "Access-Control-Allow-Origin", + "Cache-Control", + "Content-Length", + "Content-Type", + "Date", + "Request-Id", + "traceparent", + "Transfer-Encoding", + "User-Agent", + "x-ms-client-request-id", + "x-ms-date", + "x-ms-error-code", + "x-ms-request-id", + "x-ms-return-client-request-id", + "x-ms-version", + "Accept-Ranges", + "Content-Disposition", + "Content-Encoding", + "Content-Language", + "Content-MD5", + "Content-Range", + "ETag", + "Last-Modified", + "Server", + "Vary", + "x-ms-content-crc64", + "x-ms-copy-action", + "x-ms-copy-completion-time", + "x-ms-copy-id", + "x-ms-copy-progress", + "x-ms-copy-status", + "x-ms-has-immutability-policy", + "x-ms-has-legal-hold", + "x-ms-lease-state", + "x-ms-lease-status", + "x-ms-range", + "x-ms-request-server-encrypted", + "x-ms-server-encrypted", + "x-ms-snapshot", + "x-ms-source-range", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "x-ms-access-tier", + "x-ms-access-tier-change-time", + "x-ms-access-tier-inferred", + "x-ms-account-kind", + "x-ms-archive-status", + "x-ms-blob-append-offset", + "x-ms-blob-cache-control", + "x-ms-blob-committed-block-count", + "x-ms-blob-condition-appendpos", + "x-ms-blob-condition-maxsize", + "x-ms-blob-content-disposition", + "x-ms-blob-content-encoding", + "x-ms-blob-content-language", + "x-ms-blob-content-length", + "x-ms-blob-content-md5", + "x-ms-blob-content-type", + "x-ms-blob-public-access", + "x-ms-blob-sequence-number", + "x-ms-blob-type", + "x-ms-copy-destination-snapshot", + "x-ms-creation-time", + "x-ms-default-encryption-scope", + "x-ms-delete-snapshots", + "x-ms-delete-type-permanent", + "x-ms-deny-encryption-scope-override", + "x-ms-encryption-algorithm", + "x-ms-if-sequence-number-eq", + "x-ms-if-sequence-number-le", + "x-ms-if-sequence-number-lt", + "x-ms-incremental-copy", + "x-ms-lease-action", + "x-ms-lease-break-period", + "x-ms-lease-duration", + "x-ms-lease-id", + "x-ms-lease-time", + "x-ms-page-write", + "x-ms-proposed-lease-id", + "x-ms-range-get-content-md5", + "x-ms-rehydrate-priority", + "x-ms-sequence-number-action", + "x-ms-sku-name", + "x-ms-source-content-md5", + "x-ms-source-if-match", + "x-ms-source-if-modified-since", + "x-ms-source-if-none-match", + "x-ms-source-if-unmodified-since", + "x-ms-tag-count", + "x-ms-encryption-key-sha256", + "x-ms-copy-source-error-code", + "x-ms-copy-source-status-code", + "x-ms-if-tags", + "x-ms-source-if-tags" + ]; + var StorageBlobLoggingAllowedQueryParameters = [ + "comp", + "maxresults", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct", + "se", + "si", + "sip", + "sp", + "spr", + "sr", + "srt", + "ss", + "st", + "sv", + "include", + "marker", + "prefix", + "copyid", + "restype", + "blockid", + "blocklisttype", + "delimiter", + "prevsnapshot", + "ske", + "skoid", + "sks", + "skt", + "sktid", + "skv", + "snapshot" + ]; + var BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption"; + var BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption"; + var PathStylePorts = [ + "10000", + "10001", + "10002", + "10003", + "10004", + "10100", + "10101", + "10102", + "10103", + "10104", + "11000", + "11001", + "11002", + "11003", + "11004", + "11100", + "11101", + "11102", + "11103", + "11104" + ]; + function escapeURLPath(url2) { + const urlParsed = new URL(url2); + let path2 = urlParsed.pathname; + path2 = path2 || "/"; + path2 = escape2(path2); + urlParsed.pathname = path2; + return urlParsed.toString(); + } + function getProxyUriFromDevConnString(connectionString) { + let proxyUri = ""; + if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { + const matchCredentials = connectionString.split(";"); + for (const element of matchCredentials) { + if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { + proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; + } + } + } + return proxyUri; + } + function getValueInConnString(connectionString, argument) { + const elements = connectionString.split(";"); + for (const element of elements) { + if (element.trim().startsWith(argument)) { + return element.trim().match(argument + "=(.*)")[1]; + } + } + return ""; + } + function extractConnectionStringParts(connectionString) { + let proxyUri = ""; + if (connectionString.startsWith("UseDevelopmentStorage=true")) { + proxyUri = getProxyUriFromDevConnString(connectionString); + connectionString = DevelopmentConnectionString; + } + let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); + blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; + if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { + let defaultEndpointsProtocol = ""; + let accountName = ""; + let accountKey = Buffer.from("accountKey", "base64"); + let endpointSuffix = ""; + accountName = getValueInConnString(connectionString, "AccountName"); + accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); + if (!blobEndpoint) { + defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); + const protocol = defaultEndpointsProtocol.toLowerCase(); + if (protocol !== "https" && protocol !== "http") { + throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); + } + endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); + if (!endpointSuffix) { + throw new Error("Invalid EndpointSuffix in the provided Connection String"); + } + blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; + } + if (!accountName) { + throw new Error("Invalid AccountName in the provided Connection String"); + } else if (accountKey.length === 0) { + throw new Error("Invalid AccountKey in the provided Connection String"); + } + return { + kind: "AccountConnString", + url: blobEndpoint, + accountName, + accountKey, + proxyUri + }; + } else { + let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); + let accountName = getValueInConnString(connectionString, "AccountName"); + if (!accountName) { + accountName = getAccountNameFromUrl(blobEndpoint); + } + if (!blobEndpoint) { + throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); + } else if (!accountSas) { + throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + } + if (accountSas.startsWith("?")) { + accountSas = accountSas.substring(1); + } + return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; + } + } + function escape2(text) { + return encodeURIComponent(text).replace(/%2F/g, "/").replace(/'/g, "%27").replace(/\+/g, "%20").replace(/%25/g, "%"); + } + function appendToURLPath(url2, name) { + const urlParsed = new URL(url2); + let path2 = urlParsed.pathname; + path2 = path2 ? path2.endsWith("/") ? `${path2}${name}` : `${path2}/${name}` : name; + urlParsed.pathname = path2; + return urlParsed.toString(); + } + function setURLParameter(url2, name, value) { + const urlParsed = new URL(url2); + const encodedName = encodeURIComponent(name); + const encodedValue = value ? encodeURIComponent(value) : void 0; + const searchString = urlParsed.search === "" ? "?" : urlParsed.search; + const searchPieces = []; + for (const pair of searchString.slice(1).split("&")) { + if (pair) { + const [key] = pair.split("=", 2); + if (key !== encodedName) { + searchPieces.push(pair); + } + } + } + if (encodedValue) { + searchPieces.push(`${encodedName}=${encodedValue}`); + } + urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return urlParsed.toString(); + } + function getURLParameter(url2, name) { + var _a; + const urlParsed = new URL(url2); + return (_a = urlParsed.searchParams.get(name)) !== null && _a !== void 0 ? _a : void 0; + } + function setURLHost(url2, host) { + const urlParsed = new URL(url2); + urlParsed.hostname = host; + return urlParsed.toString(); + } + function getURLPath(url2) { + try { + const urlParsed = new URL(url2); + return urlParsed.pathname; + } catch (e) { + return void 0; + } + } + function getURLScheme(url2) { + try { + const urlParsed = new URL(url2); + return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; + } catch (e) { + return void 0; + } + } + function getURLPathAndQuery(url2) { + const urlParsed = new URL(url2); + const pathString = urlParsed.pathname; + if (!pathString) { + throw new RangeError("Invalid url without valid path."); + } + let queryString = urlParsed.search || ""; + queryString = queryString.trim(); + if (queryString !== "") { + queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; + } + return `${pathString}${queryString}`; + } + function getURLQueries(url2) { + let queryString = new URL(url2).search; + if (!queryString) { + return {}; + } + queryString = queryString.trim(); + queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; + let querySubStrings = queryString.split("&"); + querySubStrings = querySubStrings.filter((value) => { + const indexOfEqual = value.indexOf("="); + const lastIndexOfEqual = value.lastIndexOf("="); + return indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1; + }); + const queries = {}; + for (const querySubString of querySubStrings) { + const splitResults = querySubString.split("="); + const key = splitResults[0]; + const value = splitResults[1]; + queries[key] = value; + } + return queries; + } + function appendToURLQuery(url2, queryParts) { + const urlParsed = new URL(url2); + let query = urlParsed.search; + if (query) { + query += "&" + queryParts; + } else { + query = queryParts; + } + urlParsed.search = query; + return urlParsed.toString(); + } + function truncatedISO8061Date(date, withMilliseconds = true) { + const dateString = date.toISOString(); + return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000Z" : dateString.substring(0, dateString.length - 5) + "Z"; + } + function base64encode(content) { + return !coreUtil.isNode ? btoa(content) : Buffer.from(content).toString("base64"); + } + function generateBlockID(blockIDPrefix, blockIndex) { + const maxSourceStringLength = 48; + const maxBlockIndexLength = 6; + const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; + if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { + blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + } + const res = blockIDPrefix + padStart2(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); + return base64encode(res); + } + async function delay2(timeInMs, aborter, abortError) { + return new Promise((resolve2, reject) => { + let timeout; + const abortHandler = () => { + if (timeout !== void 0) { + clearTimeout(timeout); + } + reject(abortError); + }; + const resolveHandler = () => { + if (aborter !== void 0) { + aborter.removeEventListener("abort", abortHandler); + } + resolve2(); + }; + timeout = setTimeout(resolveHandler, timeInMs); + if (aborter !== void 0) { + aborter.addEventListener("abort", abortHandler); + } + }); + } + function padStart2(currentString, targetLength, padString = " ") { + if (String.prototype.padStart) { + return currentString.padStart(targetLength, padString); + } + padString = padString || " "; + if (currentString.length > targetLength) { + return currentString; + } else { + targetLength = targetLength - currentString.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength / padString.length); + } + return padString.slice(0, targetLength) + currentString; + } + } + function iEqual(str1, str2) { + return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); + } + function getAccountNameFromUrl(url2) { + const parsedUrl = new URL(url2); + let accountName; + try { + if (parsedUrl.hostname.split(".")[1] === "blob") { + accountName = parsedUrl.hostname.split(".")[0]; + } else if (isIpEndpointStyle(parsedUrl)) { + accountName = parsedUrl.pathname.split("/")[1]; + } else { + accountName = ""; + } + return accountName; + } catch (error2) { + throw new Error("Unable to extract accountName with provided information."); + } + } + function isIpEndpointStyle(parsedUrl) { + const host = parsedUrl.host; + return /^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) || Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port); + } + function toBlobTagsString(tags2) { + if (tags2 === void 0) { + return void 0; + } + const tagPairs = []; + for (const key in tags2) { + if (Object.prototype.hasOwnProperty.call(tags2, key)) { + const value = tags2[key]; + tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); + } + } + return tagPairs.join("&"); + } + function toBlobTags(tags2) { + if (tags2 === void 0) { + return void 0; + } + const res = { + blobTagSet: [] + }; + for (const key in tags2) { + if (Object.prototype.hasOwnProperty.call(tags2, key)) { + const value = tags2[key]; + res.blobTagSet.push({ + key, + value + }); + } + } + return res; + } + function toTags(tags2) { + if (tags2 === void 0) { + return void 0; + } + const res = {}; + for (const blobTag of tags2.blobTagSet) { + res[blobTag.key] = blobTag.value; + } + return res; + } + function toQuerySerialization(textConfiguration) { + if (textConfiguration === void 0) { + return void 0; + } + switch (textConfiguration.kind) { + case "csv": + return { + format: { + type: "delimited", + delimitedTextConfiguration: { + columnSeparator: textConfiguration.columnSeparator || ",", + fieldQuote: textConfiguration.fieldQuote || "", + recordSeparator: textConfiguration.recordSeparator, + escapeChar: textConfiguration.escapeCharacter || "", + headersPresent: textConfiguration.hasHeaders || false + } + } + }; + case "json": + return { + format: { + type: "json", + jsonTextConfiguration: { + recordSeparator: textConfiguration.recordSeparator + } + } + }; + case "arrow": + return { + format: { + type: "arrow", + arrowConfiguration: { + schema: textConfiguration.schema + } + } + }; + case "parquet": + return { + format: { + type: "parquet" + } + }; + default: + throw Error("Invalid BlobQueryTextConfiguration."); + } + } + function parseObjectReplicationRecord(objectReplicationRecord) { + if (!objectReplicationRecord) { + return void 0; + } + if ("policy-id" in objectReplicationRecord) { + return void 0; + } + const orProperties = []; + for (const key in objectReplicationRecord) { + const ids = key.split("_"); + const policyPrefix = "or-"; + if (ids[0].startsWith(policyPrefix)) { + ids[0] = ids[0].substring(policyPrefix.length); + } + const rule = { + ruleId: ids[1], + replicationStatus: objectReplicationRecord[key] + }; + const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); + if (policyIndex > -1) { + orProperties[policyIndex].rules.push(rule); + } else { + orProperties.push({ + policyId: ids[0], + rules: [rule] + }); + } + } + return orProperties; + } + function httpAuthorizationToString(httpAuthorization) { + return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : void 0; + } + function BlobNameToString(name) { + if (name.encoded) { + return decodeURIComponent(name.content); + } else { + return name.content; + } + } + function ConvertInternalResponseOfListBlobFlat(internalResponse) { + return Object.assign(Object.assign({}, internalResponse), { segment: { + blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); + return blobItem; + }) + } }); + } + function ConvertInternalResponseOfListBlobHierarchy(internalResponse) { + var _a; + return Object.assign(Object.assign({}, internalResponse), { segment: { + blobPrefixes: (_a = internalResponse.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { + const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); + return blobPrefix; + }), + blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); + return blobItem; + }) + } }); + } + function* ExtractPageRangeInfoItems(getPageRangesSegment) { + let pageRange = []; + let clearRange = []; + if (getPageRangesSegment.pageRange) + pageRange = getPageRangesSegment.pageRange; + if (getPageRangesSegment.clearRange) + clearRange = getPageRangesSegment.clearRange; + let pageRangeIndex = 0; + let clearRangeIndex = 0; + while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { + if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { + yield { + start: pageRange[pageRangeIndex].start, + end: pageRange[pageRangeIndex].end, + isClear: false + }; + ++pageRangeIndex; + } else { + yield { + start: clearRange[clearRangeIndex].start, + end: clearRange[clearRangeIndex].end, + isClear: true + }; + ++clearRangeIndex; + } + } + for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { + yield { + start: pageRange[pageRangeIndex].start, + end: pageRange[pageRangeIndex].end, + isClear: false + }; + } + for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { + yield { + start: clearRange[clearRangeIndex].start, + end: clearRange[clearRangeIndex].end, + isClear: true + }; + } + } + function EscapePath(blobName) { + const split = blobName.split("/"); + for (let i = 0; i < split.length; i++) { + split[i] = encodeURIComponent(split[i]); + } + return split.join("/"); + } + function assertResponse(response) { + if (`_response` in response) { + return response; + } + throw new TypeError(`Unexpected response object ${response}`); + } + exports2.StorageRetryPolicyType = void 0; + (function(StorageRetryPolicyType2) { + StorageRetryPolicyType2[StorageRetryPolicyType2["EXPONENTIAL"] = 0] = "EXPONENTIAL"; + StorageRetryPolicyType2[StorageRetryPolicyType2["FIXED"] = 1] = "FIXED"; + })(exports2.StorageRetryPolicyType || (exports2.StorageRetryPolicyType = {})); + var DEFAULT_RETRY_OPTIONS$1 = { + maxRetryDelayInMs: 120 * 1e3, + maxTries: 4, + retryDelayInMs: 4 * 1e3, + retryPolicyType: exports2.StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: void 0 + // Use server side default timeout strategy + }; + var RETRY_ABORT_ERROR$1 = new abortController.AbortError("The operation was aborted."); + var StorageRetryPolicy = class extends BaseRequestPolicy { + /** + * Creates an instance of RetryPolicy. + * + * @param nextPolicy - + * @param options - + * @param retryOptions - + */ + constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS$1) { + super(nextPolicy, options); + this.retryOptions = { + retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS$1.retryPolicyType, + maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS$1.maxTries, + tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS$1.tryTimeoutInMs, + retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs) : DEFAULT_RETRY_OPTIONS$1.retryDelayInMs, + maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs, + secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS$1.secondaryHost + }; + } + /** + * Sends request. + * + * @param request - + */ + async sendRequest(request) { + return this.attemptSendRequest(request, false, 1); + } + /** + * Decide and perform next retry. Won't mutate request parameter. + * + * @param request - + * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then + * the resource was not found. This may be due to replication delay. So, in this + * case, we'll never try the secondary again for this operation. + * @param attempt - How many retries has been attempted to performed, starting from 1, which includes + * the attempt will be performed by this method call. + */ + async attemptSendRequest(request, secondaryHas404, attempt) { + const newRequest = request.clone(); + const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || attempt % 2 === 1; + if (!isPrimaryRetry) { + newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); + } + if (this.retryOptions.tryTimeoutInMs) { + newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1e3).toString()); + } + let response; + try { + logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await this._nextPolicy.sendRequest(newRequest); + if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { + return response; + } + secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; + } catch (err) { + logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); + if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { + throw err; + } + } + await this.delay(isPrimaryRetry, attempt, request.abortSignal); + return this.attemptSendRequest(request, secondaryHas404, ++attempt); + } + /** + * Decide whether to retry according to last HTTP response and retry counters. + * + * @param isPrimaryRetry - + * @param attempt - + * @param response - + * @param err - + */ + shouldRetry(isPrimaryRetry, attempt, response, err) { + if (attempt >= this.retryOptions.maxTries) { + logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions.maxTries}, no further try.`); + return false; + } + const retriableErrors2 = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR" + // For default xhr based http client provided in ms-rest-js + ]; + if (err) { + for (const retriableError of retriableErrors2) { + if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || err.code && err.code.toString().toUpperCase() === retriableError) { + logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); + return true; + } + } + } + if (response || err) { + const statusCode = response ? response.status : err ? err.statusCode : 0; + if (!isPrimaryRetry && statusCode === 404) { + logger.info(`RetryPolicy: Secondary access with 404, will retry.`); + return true; + } + if (statusCode === 503 || statusCode === 500) { + logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); + return true; + } + } + if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith(`Error "Error: Unclosed root tag`))) { + logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); + return true; + } + return false; + } + /** + * Delay a calculated time between retries. + * + * @param isPrimaryRetry - + * @param attempt - + * @param abortSignal - + */ + async delay(isPrimaryRetry, attempt, abortSignal) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (this.retryOptions.retryPolicyType) { + case exports2.StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); + break; + case exports2.StorageRetryPolicyType.FIXED: + delayTimeInMs = this.retryOptions.retryDelayInMs; + break; + } + } else { + delayTimeInMs = Math.random() * 1e3; + } + logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delay2(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR$1); + } + }; + var StorageRetryPolicyFactory = class { + /** + * Creates an instance of StorageRetryPolicyFactory. + * @param retryOptions - + */ + constructor(retryOptions) { + this.retryOptions = retryOptions; + } + /** + * Creates a StorageRetryPolicy object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); + } + }; + var CredentialPolicy = class extends BaseRequestPolicy { + /** + * Sends out request. + * + * @param request - + */ + sendRequest(request) { + return this._nextPolicy.sendRequest(this.signRequest(request)); + } + /** + * Child classes must implement this method with request signing. This method + * will be executed in {@link sendRequest}. + * + * @param request - + */ + signRequest(request) { + return request; + } + }; + var table_lv0 = new Uint32Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1820, + 0, + 1823, + 1825, + 1827, + 1829, + 0, + 0, + 0, + 1837, + 2051, + 0, + 0, + 1843, + 0, + 3331, + 3354, + 3356, + 3358, + 3360, + 3362, + 3364, + 3366, + 3368, + 3370, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 3586, + 3593, + 3594, + 3610, + 3617, + 3619, + 3621, + 3628, + 3634, + 3637, + 3638, + 3656, + 3665, + 3696, + 3708, + 3710, + 3721, + 3722, + 3729, + 3737, + 3743, + 3746, + 3748, + 3750, + 3751, + 3753, + 0, + 0, + 0, + 1859, + 1860, + 1864, + 3586, + 3593, + 3594, + 3610, + 3617, + 3619, + 3621, + 3628, + 3634, + 3637, + 3638, + 3656, + 3665, + 3696, + 3708, + 3710, + 3721, + 3722, + 3729, + 3737, + 3743, + 3746, + 3748, + 3750, + 3751, + 3753, + 0, + 1868, + 0, + 1872, + 0 + ]); + var table_lv2 = new Uint32Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]); + var table_lv4 = new Uint32Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 32786, + 0, + 0, + 0, + 0, + 0, + 33298, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]); + function compareHeader(lhs, rhs) { + if (isLessThan(lhs, rhs)) + return -1; + return 1; + } + function isLessThan(lhs, rhs) { + const tables = [table_lv0, table_lv2, table_lv4]; + let curr_level = 0; + let i = 0; + let j = 0; + while (curr_level < tables.length) { + if (curr_level === tables.length - 1 && i !== j) { + return i > j; + } + const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 1; + const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 1; + if (weight1 === 1 && weight2 === 1) { + i = 0; + j = 0; + ++curr_level; + } else if (weight1 === weight2) { + ++i; + ++j; + } else if (weight1 === 0) { + ++i; + } else if (weight2 === 0) { + ++j; + } else { + return weight1 < weight2; + } + } + return false; + } + var StorageSharedKeyCredentialPolicy = class extends CredentialPolicy { + /** + * Creates an instance of StorageSharedKeyCredentialPolicy. + * @param nextPolicy - + * @param options - + * @param factory - + */ + constructor(nextPolicy, options, factory) { + super(nextPolicy, options); + this.factory = factory; + } + /** + * Signs request. + * + * @param request - + */ + signRequest(request) { + request.headers.set(HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); + if (request.body && (typeof request.body === "string" || request.body !== void 0) && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + const stringToSign = [ + request.method.toUpperCase(), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), + this.getHeaderValueToSign(request, HeaderConstants.DATE), + this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), + this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), + this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), + this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), + this.getHeaderValueToSign(request, HeaderConstants.RANGE) + ].join("\n") + "\n" + this.getCanonicalizedHeadersString(request) + this.getCanonicalizedResourceString(request); + const signature = this.factory.computeHMACSHA256(stringToSign); + request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); + return request; + } + /** + * Retrieve header value according to shared key sign rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key + * + * @param request - + * @param headerName - + */ + getHeaderValueToSign(request, headerName) { + const value = request.headers.get(headerName); + if (!value) { + return ""; + } + if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { + return ""; + } + return value; + } + /** + * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: + * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. + * 2. Convert each HTTP header name to lowercase. + * 3. Sort the headers lexicographically by header name, in ascending order. + * Each header may appear only once in the string. + * 4. Replace any linear whitespace in the header value with a single space. + * 5. Trim any whitespace around the colon in the header. + * 6. Finally, append a new-line character to each canonicalized header in the resulting list. + * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. + * + * @param request - + */ + getCanonicalizedHeadersString(request) { + let headersArray = request.headers.headersArray().filter((value) => { + return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); + }); + headersArray.sort((a, b) => { + return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); + }); + headersArray = headersArray.filter((value, index, array) => { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { + return false; + } + return true; + }); + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} +`; + }); + return canonicalizedHeadersStringToSign; + } + /** + * Retrieves the webResource canonicalized resource string. + * + * @param request - + */ + getCanonicalizedResourceString(request) { + const path2 = getURLPath(request.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${this.factory.accountName}${path2}`; + const queries = getURLQueries(request.url); + const lowercaseQueries = {}; + if (queries) { + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); + lowercaseQueries[lowercaseKey] = queries[key]; + queryKeys.push(lowercaseKey); + } + } + queryKeys.sort(); + for (const key of queryKeys) { + canonicalizedResourceString += ` +${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } + } + return canonicalizedResourceString; + } + }; + var Credential2 = class { + /** + * Creates a RequestPolicy object. + * + * @param _nextPolicy - + * @param _options - + */ + create(_nextPolicy, _options) { + throw new Error("Method should be implemented in children classes."); + } + }; + var StorageSharedKeyCredential = class extends Credential2 { + /** + * Creates an instance of StorageSharedKeyCredential. + * @param accountName - + * @param accountKey - + */ + constructor(accountName, accountKey) { + super(); + this.accountName = accountName; + this.accountKey = Buffer.from(accountKey, "base64"); + } + /** + * Creates a StorageSharedKeyCredentialPolicy object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); + } + /** + * Generates a hash signature for an HTTP request or for a SAS. + * + * @param stringToSign - + */ + computeHMACSHA256(stringToSign) { + return crypto.createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); + } + }; + var AnonymousCredentialPolicy = class extends CredentialPolicy { + /** + * Creates an instance of AnonymousCredentialPolicy. + * @param nextPolicy - + * @param options - + */ + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + }; + var AnonymousCredential = class extends Credential2 { + /** + * Creates an {@link AnonymousCredentialPolicy} object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new AnonymousCredentialPolicy(nextPolicy, options); + } + }; + var _defaultHttpClient; + function getCachedDefaultHttpClient() { + if (!_defaultHttpClient) { + _defaultHttpClient = coreRestPipeline.createDefaultHttpClient(); + } + return _defaultHttpClient; + } + var storageBrowserPolicyName = "storageBrowserPolicy"; + function storageBrowserPolicy() { + return { + name: storageBrowserPolicyName, + async sendRequest(request, next) { + if (coreUtil.isNode) { + return next(request); + } + if (request.method === "GET" || request.method === "HEAD") { + request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); + } + request.headers.delete(HeaderConstants.COOKIE); + request.headers.delete(HeaderConstants.CONTENT_LENGTH); + return next(request); + } + }; + } + var storageRetryPolicyName = "storageRetryPolicy"; + var StorageRetryPolicyType; + (function(StorageRetryPolicyType2) { + StorageRetryPolicyType2[StorageRetryPolicyType2["EXPONENTIAL"] = 0] = "EXPONENTIAL"; + StorageRetryPolicyType2[StorageRetryPolicyType2["FIXED"] = 1] = "FIXED"; + })(StorageRetryPolicyType || (StorageRetryPolicyType = {})); + var DEFAULT_RETRY_OPTIONS = { + maxRetryDelayInMs: 120 * 1e3, + maxTries: 4, + retryDelayInMs: 4 * 1e3, + retryPolicyType: StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: void 0 + // Use server side default timeout strategy + }; + var retriableErrors = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR" + ]; + var RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); + function storageRetryPolicy(options = {}) { + var _a, _b, _c, _d, _e, _f; + const retryPolicyType = (_a = options.retryPolicyType) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_OPTIONS.retryPolicyType; + const maxTries = (_b = options.maxTries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_OPTIONS.maxTries; + const retryDelayInMs = (_c = options.retryDelayInMs) !== null && _c !== void 0 ? _c : DEFAULT_RETRY_OPTIONS.retryDelayInMs; + const maxRetryDelayInMs = (_d = options.maxRetryDelayInMs) !== null && _d !== void 0 ? _d : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; + const secondaryHost = (_e = options.secondaryHost) !== null && _e !== void 0 ? _e : DEFAULT_RETRY_OPTIONS.secondaryHost; + const tryTimeoutInMs = (_f = options.tryTimeoutInMs) !== null && _f !== void 0 ? _f : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; + function shouldRetry({ isPrimaryRetry, attempt, response, error: error2 }) { + var _a2, _b2; + if (attempt >= maxTries) { + logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); + return false; + } + if (error2) { + for (const retriableError of retriableErrors) { + if (error2.name.toUpperCase().includes(retriableError) || error2.message.toUpperCase().includes(retriableError) || error2.code && error2.code.toString().toUpperCase() === retriableError) { + logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); + return true; + } + } + if ((error2 === null || error2 === void 0 ? void 0 : error2.code) === "PARSE_ERROR" && (error2 === null || error2 === void 0 ? void 0 : error2.message.startsWith(`Error "Error: Unclosed root tag`))) { + logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); + return true; + } + } + if (response || error2) { + const statusCode = (_b2 = (_a2 = response === null || response === void 0 ? void 0 : response.status) !== null && _a2 !== void 0 ? _a2 : error2 === null || error2 === void 0 ? void 0 : error2.statusCode) !== null && _b2 !== void 0 ? _b2 : 0; + if (!isPrimaryRetry && statusCode === 404) { + logger.info(`RetryPolicy: Secondary access with 404, will retry.`); + return true; + } + if (statusCode === 503 || statusCode === 500) { + logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); + return true; + } + } + return false; + } + function calculateDelay(isPrimaryRetry, attempt) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (retryPolicyType) { + case StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs); + break; + case StorageRetryPolicyType.FIXED: + delayTimeInMs = retryDelayInMs; + break; + } + } else { + delayTimeInMs = Math.random() * 1e3; + } + logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delayTimeInMs; + } + return { + name: storageRetryPolicyName, + async sendRequest(request, next) { + if (tryTimeoutInMs) { + request.url = setURLParameter(request.url, URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1e3))); + } + const primaryUrl = request.url; + const secondaryUrl = secondaryHost ? setURLHost(request.url, secondaryHost) : void 0; + let secondaryHas404 = false; + let attempt = 1; + let retryAgain = true; + let response; + let error2; + while (retryAgain) { + const isPrimaryRetry = secondaryHas404 || !secondaryUrl || !["GET", "HEAD", "OPTIONS"].includes(request.method) || attempt % 2 === 1; + request.url = isPrimaryRetry ? primaryUrl : secondaryUrl; + response = void 0; + error2 = void 0; + try { + logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await next(request); + secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; + } catch (e) { + if (coreRestPipeline.isRestError(e)) { + logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); + error2 = e; + } else { + logger.error(`RetryPolicy: Caught error, message: ${coreUtil.getErrorMessage(e)}`); + throw e; + } + } + retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error: error2 }); + if (retryAgain) { + await delay2(calculateDelay(isPrimaryRetry, attempt), request.abortSignal, RETRY_ABORT_ERROR); + } + attempt++; + } + if (response) { + return response; + } + throw error2 !== null && error2 !== void 0 ? error2 : new coreRestPipeline.RestError("RetryPolicy failed without known error."); + } + }; + } + var storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy"; + function storageSharedKeyCredentialPolicy(options) { + function signRequest(request) { + request.headers.set(HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); + if (request.body && (typeof request.body === "string" || Buffer.isBuffer(request.body)) && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + const stringToSign = [ + request.method.toUpperCase(), + getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), + getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), + getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), + getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), + getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), + getHeaderValueToSign(request, HeaderConstants.DATE), + getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), + getHeaderValueToSign(request, HeaderConstants.IF_MATCH), + getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), + getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), + getHeaderValueToSign(request, HeaderConstants.RANGE) + ].join("\n") + "\n" + getCanonicalizedHeadersString(request) + getCanonicalizedResourceString(request); + const signature = crypto.createHmac("sha256", options.accountKey).update(stringToSign, "utf8").digest("base64"); + request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`); + } + function getHeaderValueToSign(request, headerName) { + const value = request.headers.get(headerName); + if (!value) { + return ""; + } + if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { + return ""; + } + return value; + } + function getCanonicalizedHeadersString(request) { + let headersArray = []; + for (const [name, value] of request.headers) { + if (name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE)) { + headersArray.push({ name, value }); + } + } + headersArray.sort((a, b) => { + return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); + }); + headersArray = headersArray.filter((value, index, array) => { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { + return false; + } + return true; + }); + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} +`; + }); + return canonicalizedHeadersStringToSign; + } + function getCanonicalizedResourceString(request) { + const path2 = getURLPath(request.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${options.accountName}${path2}`; + const queries = getURLQueries(request.url); + const lowercaseQueries = {}; + if (queries) { + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); + lowercaseQueries[lowercaseKey] = queries[key]; + queryKeys.push(lowercaseKey); + } + } + queryKeys.sort(); + for (const key of queryKeys) { + canonicalizedResourceString += ` +${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } + } + return canonicalizedResourceString; + } + return { + name: storageSharedKeyCredentialPolicyName, + async sendRequest(request, next) { + signRequest(request); + return next(request); + } + }; + } + var StorageBrowserPolicy = class extends BaseRequestPolicy { + /** + * Creates an instance of StorageBrowserPolicy. + * @param nextPolicy - + * @param options - + */ + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + /** + * Sends out request. + * + * @param request - + */ + async sendRequest(request) { + if (coreUtil.isNode) { + return this._nextPolicy.sendRequest(request); + } + if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { + request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); + } + request.headers.remove(HeaderConstants.COOKIE); + request.headers.remove(HeaderConstants.CONTENT_LENGTH); + return this._nextPolicy.sendRequest(request); + } + }; + var StorageBrowserPolicyFactory = class { + /** + * Creates a StorageBrowserPolicyFactory object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageBrowserPolicy(nextPolicy, options); + } + }; + var storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; + function storageCorrectContentLengthPolicy() { + function correctContentLength(request) { + if (request.body && (typeof request.body === "string" || Buffer.isBuffer(request.body)) && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + } + return { + name: storageCorrectContentLengthPolicyName, + async sendRequest(request, next) { + correctContentLength(request); + return next(request); + } + }; + } + function isPipelineLike(pipeline) { + if (!pipeline || typeof pipeline !== "object") { + return false; + } + const castPipeline = pipeline; + return Array.isArray(castPipeline.factories) && typeof castPipeline.options === "object" && typeof castPipeline.toServiceClientOptions === "function"; + } + var Pipeline = class { + /** + * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. + * + * @param factories - + * @param options - + */ + constructor(factories, options = {}) { + this.factories = factories; + this.options = options; + } + /** + * Transfer Pipeline object to ServiceClientOptions object which is required by + * ServiceClient constructor. + * + * @returns The ServiceClientOptions object from this Pipeline. + */ + toServiceClientOptions() { + return { + httpClient: this.options.httpClient, + requestPolicyFactories: this.factories + }; + } + }; + function newPipeline(credential, pipelineOptions = {}) { + if (!credential) { + credential = new AnonymousCredential(); + } + const pipeline = new Pipeline([], pipelineOptions); + pipeline._credential = credential; + return pipeline; + } + function processDownlevelPipeline(pipeline) { + const knownFactoryFunctions = [ + isAnonymousCredential, + isStorageSharedKeyCredential, + isCoreHttpBearerTokenFactory, + isStorageBrowserPolicyFactory, + isStorageRetryPolicyFactory, + isStorageTelemetryPolicyFactory, + isCoreHttpPolicyFactory + ]; + if (pipeline.factories.length) { + const novelFactories = pipeline.factories.filter((factory) => { + return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory)); + }); + if (novelFactories.length) { + const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory)); + return { + wrappedPolicies: coreHttpCompat.createRequestPolicyFactoryPolicy(novelFactories), + afterRetry: hasInjector + }; + } + } + return void 0; + } + function getCoreClientOptions(pipeline) { + var _a; + const _b = pipeline.options, { httpClient: v1Client } = _b, restOptions = tslib.__rest(_b, ["httpClient"]); + let httpClient = pipeline._coreHttpClient; + if (!httpClient) { + httpClient = v1Client ? coreHttpCompat.convertHttpClient(v1Client) : getCachedDefaultHttpClient(); + pipeline._coreHttpClient = httpClient; + } + let corePipeline = pipeline._corePipeline; + if (!corePipeline) { + const packageDetails = `azsdk-js-azure-storage-blob/${SDK_VERSION}`; + const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; + corePipeline = coreClient.createClientPipeline(Object.assign(Object.assign({}, restOptions), { loggingOptions: { + additionalAllowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, + additionalAllowedQueryParameters: StorageBlobLoggingAllowedQueryParameters, + logger: logger.info + }, userAgentOptions: { + userAgentPrefix + }, serializationOptions: { + stringifyXML: coreXml.stringifyXML, + serializerOptions: { + xml: { + // Use customized XML char key of "#" so we can deserialize metadata + // with "_" key + xmlCharKey: "#" + } + } + }, deserializationOptions: { + parseXML: coreXml.parseXML, + serializerOptions: { + xml: { + // Use customized XML char key of "#" so we can deserialize metadata + // with "_" key + xmlCharKey: "#" + } + } + } })); + corePipeline.removePolicy({ phase: "Retry" }); + corePipeline.removePolicy({ name: coreRestPipeline.decompressResponsePolicyName }); + corePipeline.addPolicy(storageCorrectContentLengthPolicy()); + corePipeline.addPolicy(storageRetryPolicy(restOptions.retryOptions), { phase: "Retry" }); + corePipeline.addPolicy(storageBrowserPolicy()); + const downlevelResults = processDownlevelPipeline(pipeline); + if (downlevelResults) { + corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : void 0); + } + const credential = getCredentialFromPipeline(pipeline); + if (coreAuth.isTokenCredential(credential)) { + corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ + credential, + scopes: (_a = restOptions.audience) !== null && _a !== void 0 ? _a : StorageOAuthScopes, + challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge } + }), { phase: "Sign" }); + } else if (credential instanceof StorageSharedKeyCredential) { + corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ + accountName: credential.accountName, + accountKey: credential.accountKey + }), { phase: "Sign" }); + } + pipeline._corePipeline = corePipeline; + } + return Object.assign(Object.assign({}, restOptions), { allowInsecureConnection: true, httpClient, pipeline: corePipeline }); + } + function getCredentialFromPipeline(pipeline) { + if (pipeline._credential) { + return pipeline._credential; + } + let credential = new AnonymousCredential(); + for (const factory of pipeline.factories) { + if (coreAuth.isTokenCredential(factory.credential)) { + credential = factory.credential; + } else if (isStorageSharedKeyCredential(factory)) { + return factory; + } + } + return credential; + } + function isStorageSharedKeyCredential(factory) { + if (factory instanceof StorageSharedKeyCredential) { + return true; + } + return factory.constructor.name === "StorageSharedKeyCredential"; + } + function isAnonymousCredential(factory) { + if (factory instanceof AnonymousCredential) { + return true; + } + return factory.constructor.name === "AnonymousCredential"; + } + function isCoreHttpBearerTokenFactory(factory) { + return coreAuth.isTokenCredential(factory.credential); + } + function isStorageBrowserPolicyFactory(factory) { + if (factory instanceof StorageBrowserPolicyFactory) { + return true; + } + return factory.constructor.name === "StorageBrowserPolicyFactory"; + } + function isStorageRetryPolicyFactory(factory) { + if (factory instanceof StorageRetryPolicyFactory) { + return true; + } + return factory.constructor.name === "StorageRetryPolicyFactory"; + } + function isStorageTelemetryPolicyFactory(factory) { + return factory.constructor.name === "TelemetryPolicyFactory"; + } + function isInjectorPolicyFactory(factory) { + return factory.constructor.name === "InjectorPolicyFactory"; + } + function isCoreHttpPolicyFactory(factory) { + const knownPolicies = [ + "GenerateClientRequestIdPolicy", + "TracingPolicy", + "LogPolicy", + "ProxyPolicy", + "DisableResponseDecompressionPolicy", + "KeepAlivePolicy", + "DeserializationPolicy" + ]; + const mockHttpClient = { + sendRequest: async (request) => { + return { + request, + headers: request.headers.clone(), + status: 500 + }; + } + }; + const mockRequestPolicyOptions = { + log(_logLevel, _message) { + }, + shouldLog(_logLevel) { + return false; + } + }; + const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions); + const policyName = policyInstance.constructor.name; + return knownPolicies.some((knownPolicyName) => { + return policyName.startsWith(knownPolicyName); + }); + } + var BlobServiceProperties = { + serializedName: "BlobServiceProperties", + xmlName: "StorageServiceProperties", + type: { + name: "Composite", + className: "BlobServiceProperties", + modelProperties: { + blobAnalyticsLogging: { + serializedName: "Logging", + xmlName: "Logging", + type: { + name: "Composite", + className: "Logging" + } + }, + hourMetrics: { + serializedName: "HourMetrics", + xmlName: "HourMetrics", + type: { + name: "Composite", + className: "Metrics" + } + }, + minuteMetrics: { + serializedName: "MinuteMetrics", + xmlName: "MinuteMetrics", + type: { + name: "Composite", + className: "Metrics" + } + }, + cors: { + serializedName: "Cors", + xmlName: "Cors", + xmlIsWrapped: true, + xmlElementName: "CorsRule", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "CorsRule" + } + } + } + }, + defaultServiceVersion: { + serializedName: "DefaultServiceVersion", + xmlName: "DefaultServiceVersion", + type: { + name: "String" + } + }, + deleteRetentionPolicy: { + serializedName: "DeleteRetentionPolicy", + xmlName: "DeleteRetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + }, + staticWebsite: { + serializedName: "StaticWebsite", + xmlName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite" + } + } + } + } + }; + var Logging = { + serializedName: "Logging", + type: { + name: "Composite", + className: "Logging", + modelProperties: { + version: { + serializedName: "Version", + required: true, + xmlName: "Version", + type: { + name: "String" + } + }, + deleteProperty: { + serializedName: "Delete", + required: true, + xmlName: "Delete", + type: { + name: "Boolean" + } + }, + read: { + serializedName: "Read", + required: true, + xmlName: "Read", + type: { + name: "Boolean" + } + }, + write: { + serializedName: "Write", + required: true, + xmlName: "Write", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } + } + } + }; + var RetentionPolicy = { + serializedName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy", + modelProperties: { + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + days: { + constraints: { + InclusiveMinimum: 1 + }, + serializedName: "Days", + xmlName: "Days", + type: { + name: "Number" + } + } + } + } + }; + var Metrics = { + serializedName: "Metrics", + type: { + name: "Composite", + className: "Metrics", + modelProperties: { + version: { + serializedName: "Version", + xmlName: "Version", + type: { + name: "String" + } + }, + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + includeAPIs: { + serializedName: "IncludeAPIs", + xmlName: "IncludeAPIs", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } + } + } + }; + var CorsRule = { + serializedName: "CorsRule", + type: { + name: "Composite", + className: "CorsRule", + modelProperties: { + allowedOrigins: { + serializedName: "AllowedOrigins", + required: true, + xmlName: "AllowedOrigins", + type: { + name: "String" + } + }, + allowedMethods: { + serializedName: "AllowedMethods", + required: true, + xmlName: "AllowedMethods", + type: { + name: "String" + } + }, + allowedHeaders: { + serializedName: "AllowedHeaders", + required: true, + xmlName: "AllowedHeaders", + type: { + name: "String" + } + }, + exposedHeaders: { + serializedName: "ExposedHeaders", + required: true, + xmlName: "ExposedHeaders", + type: { + name: "String" + } + }, + maxAgeInSeconds: { + constraints: { + InclusiveMinimum: 0 + }, + serializedName: "MaxAgeInSeconds", + required: true, + xmlName: "MaxAgeInSeconds", + type: { + name: "Number" + } + } + } + } + }; + var StaticWebsite = { + serializedName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite", + modelProperties: { + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + indexDocument: { + serializedName: "IndexDocument", + xmlName: "IndexDocument", + type: { + name: "String" + } + }, + errorDocument404Path: { + serializedName: "ErrorDocument404Path", + xmlName: "ErrorDocument404Path", + type: { + name: "String" + } + }, + defaultIndexDocumentPath: { + serializedName: "DefaultIndexDocumentPath", + xmlName: "DefaultIndexDocumentPath", + type: { + name: "String" + } + } + } + } + }; + var StorageError = { + serializedName: "StorageError", + type: { + name: "Composite", + className: "StorageError", + modelProperties: { + message: { + serializedName: "Message", + xmlName: "Message", + type: { + name: "String" + } + }, + code: { + serializedName: "Code", + xmlName: "Code", + type: { + name: "String" + } + }, + authenticationErrorDetail: { + serializedName: "AuthenticationErrorDetail", + xmlName: "AuthenticationErrorDetail", + type: { + name: "String" + } + } + } + } + }; + var BlobServiceStatistics = { + serializedName: "BlobServiceStatistics", + xmlName: "StorageServiceStats", + type: { + name: "Composite", + className: "BlobServiceStatistics", + modelProperties: { + geoReplication: { + serializedName: "GeoReplication", + xmlName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication" + } + } + } + } + }; + var GeoReplication = { + serializedName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication", + modelProperties: { + status: { + serializedName: "Status", + required: true, + xmlName: "Status", + type: { + name: "Enum", + allowedValues: ["live", "bootstrap", "unavailable"] + } + }, + lastSyncOn: { + serializedName: "LastSyncTime", + required: true, + xmlName: "LastSyncTime", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var ListContainersSegmentResponse = { + serializedName: "ListContainersSegmentResponse", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "ListContainersSegmentResponse", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + prefix: { + serializedName: "Prefix", + xmlName: "Prefix", + type: { + name: "String" + } + }, + marker: { + serializedName: "Marker", + xmlName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + serializedName: "MaxResults", + xmlName: "MaxResults", + type: { + name: "Number" + } + }, + containerItems: { + serializedName: "ContainerItems", + required: true, + xmlName: "Containers", + xmlIsWrapped: true, + xmlElementName: "Container", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ContainerItem" + } + } + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } + } + }; + var ContainerItem = { + serializedName: "ContainerItem", + xmlName: "Container", + type: { + name: "Composite", + className: "ContainerItem", + modelProperties: { + name: { + serializedName: "Name", + required: true, + xmlName: "Name", + type: { + name: "String" + } + }, + deleted: { + serializedName: "Deleted", + xmlName: "Deleted", + type: { + name: "Boolean" + } + }, + version: { + serializedName: "Version", + xmlName: "Version", + type: { + name: "String" + } + }, + properties: { + serializedName: "Properties", + xmlName: "Properties", + type: { + name: "Composite", + className: "ContainerProperties" + } + }, + metadata: { + serializedName: "Metadata", + xmlName: "Metadata", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + } + } + } + }; + var ContainerProperties = { + serializedName: "ContainerProperties", + type: { + name: "Composite", + className: "ContainerProperties", + modelProperties: { + lastModified: { + serializedName: "Last-Modified", + required: true, + xmlName: "Last-Modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "Etag", + required: true, + xmlName: "Etag", + type: { + name: "String" + } + }, + leaseStatus: { + serializedName: "LeaseStatus", + xmlName: "LeaseStatus", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + leaseState: { + serializedName: "LeaseState", + xmlName: "LeaseState", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseDuration: { + serializedName: "LeaseDuration", + xmlName: "LeaseDuration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + publicAccess: { + serializedName: "PublicAccess", + xmlName: "PublicAccess", + type: { + name: "Enum", + allowedValues: ["container", "blob"] + } + }, + hasImmutabilityPolicy: { + serializedName: "HasImmutabilityPolicy", + xmlName: "HasImmutabilityPolicy", + type: { + name: "Boolean" + } + }, + hasLegalHold: { + serializedName: "HasLegalHold", + xmlName: "HasLegalHold", + type: { + name: "Boolean" + } + }, + defaultEncryptionScope: { + serializedName: "DefaultEncryptionScope", + xmlName: "DefaultEncryptionScope", + type: { + name: "String" + } + }, + preventEncryptionScopeOverride: { + serializedName: "DenyEncryptionScopeOverride", + xmlName: "DenyEncryptionScopeOverride", + type: { + name: "Boolean" + } + }, + deletedOn: { + serializedName: "DeletedTime", + xmlName: "DeletedTime", + type: { + name: "DateTimeRfc1123" + } + }, + remainingRetentionDays: { + serializedName: "RemainingRetentionDays", + xmlName: "RemainingRetentionDays", + type: { + name: "Number" + } + }, + isImmutableStorageWithVersioningEnabled: { + serializedName: "ImmutableStorageWithVersioningEnabled", + xmlName: "ImmutableStorageWithVersioningEnabled", + type: { + name: "Boolean" + } + } + } + } + }; + var KeyInfo = { + serializedName: "KeyInfo", + type: { + name: "Composite", + className: "KeyInfo", + modelProperties: { + startsOn: { + serializedName: "Start", + required: true, + xmlName: "Start", + type: { + name: "String" + } + }, + expiresOn: { + serializedName: "Expiry", + required: true, + xmlName: "Expiry", + type: { + name: "String" + } + } + } + } + }; + var UserDelegationKey = { + serializedName: "UserDelegationKey", + type: { + name: "Composite", + className: "UserDelegationKey", + modelProperties: { + signedObjectId: { + serializedName: "SignedOid", + required: true, + xmlName: "SignedOid", + type: { + name: "String" + } + }, + signedTenantId: { + serializedName: "SignedTid", + required: true, + xmlName: "SignedTid", + type: { + name: "String" + } + }, + signedStartsOn: { + serializedName: "SignedStart", + required: true, + xmlName: "SignedStart", + type: { + name: "String" + } + }, + signedExpiresOn: { + serializedName: "SignedExpiry", + required: true, + xmlName: "SignedExpiry", + type: { + name: "String" + } + }, + signedService: { + serializedName: "SignedService", + required: true, + xmlName: "SignedService", + type: { + name: "String" + } + }, + signedVersion: { + serializedName: "SignedVersion", + required: true, + xmlName: "SignedVersion", + type: { + name: "String" + } + }, + value: { + serializedName: "Value", + required: true, + xmlName: "Value", + type: { + name: "String" + } + } + } + } + }; + var FilterBlobSegment = { + serializedName: "FilterBlobSegment", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "FilterBlobSegment", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + where: { + serializedName: "Where", + required: true, + xmlName: "Where", + type: { + name: "String" + } + }, + blobs: { + serializedName: "Blobs", + required: true, + xmlName: "Blobs", + xmlIsWrapped: true, + xmlElementName: "Blob", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "FilterBlobItem" + } + } + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } + } + }; + var FilterBlobItem = { + serializedName: "FilterBlobItem", + xmlName: "Blob", + type: { + name: "Composite", + className: "FilterBlobItem", + modelProperties: { + name: { + serializedName: "Name", + required: true, + xmlName: "Name", + type: { + name: "String" + } + }, + containerName: { + serializedName: "ContainerName", + required: true, + xmlName: "ContainerName", + type: { + name: "String" + } + }, + tags: { + serializedName: "Tags", + xmlName: "Tags", + type: { + name: "Composite", + className: "BlobTags" + } + } + } + } + }; + var BlobTags = { + serializedName: "BlobTags", + xmlName: "Tags", + type: { + name: "Composite", + className: "BlobTags", + modelProperties: { + blobTagSet: { + serializedName: "BlobTagSet", + required: true, + xmlName: "TagSet", + xmlIsWrapped: true, + xmlElementName: "Tag", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobTag" + } + } + } + } + } + } + }; + var BlobTag = { + serializedName: "BlobTag", + xmlName: "Tag", + type: { + name: "Composite", + className: "BlobTag", + modelProperties: { + key: { + serializedName: "Key", + required: true, + xmlName: "Key", + type: { + name: "String" + } + }, + value: { + serializedName: "Value", + required: true, + xmlName: "Value", + type: { + name: "String" + } + } + } + } + }; + var SignedIdentifier = { + serializedName: "SignedIdentifier", + xmlName: "SignedIdentifier", + type: { + name: "Composite", + className: "SignedIdentifier", + modelProperties: { + id: { + serializedName: "Id", + required: true, + xmlName: "Id", + type: { + name: "String" + } + }, + accessPolicy: { + serializedName: "AccessPolicy", + xmlName: "AccessPolicy", + type: { + name: "Composite", + className: "AccessPolicy" + } + } + } + } + }; + var AccessPolicy = { + serializedName: "AccessPolicy", + type: { + name: "Composite", + className: "AccessPolicy", + modelProperties: { + startsOn: { + serializedName: "Start", + xmlName: "Start", + type: { + name: "String" + } + }, + expiresOn: { + serializedName: "Expiry", + xmlName: "Expiry", + type: { + name: "String" + } + }, + permissions: { + serializedName: "Permission", + xmlName: "Permission", + type: { + name: "String" + } + } + } + } + }; + var ListBlobsFlatSegmentResponse = { + serializedName: "ListBlobsFlatSegmentResponse", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "ListBlobsFlatSegmentResponse", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + containerName: { + serializedName: "ContainerName", + required: true, + xmlName: "ContainerName", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + prefix: { + serializedName: "Prefix", + xmlName: "Prefix", + type: { + name: "String" + } + }, + marker: { + serializedName: "Marker", + xmlName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + serializedName: "MaxResults", + xmlName: "MaxResults", + type: { + name: "Number" + } + }, + segment: { + serializedName: "Segment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobFlatListSegment" + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } + } + }; + var BlobFlatListSegment = { + serializedName: "BlobFlatListSegment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobFlatListSegment", + modelProperties: { + blobItems: { + serializedName: "BlobItems", + required: true, + xmlName: "BlobItems", + xmlElementName: "Blob", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobItemInternal" + } + } + } + } + } + } + }; + var BlobItemInternal = { + serializedName: "BlobItemInternal", + xmlName: "Blob", + type: { + name: "Composite", + className: "BlobItemInternal", + modelProperties: { + name: { + serializedName: "Name", + xmlName: "Name", + type: { + name: "Composite", + className: "BlobName" + } + }, + deleted: { + serializedName: "Deleted", + required: true, + xmlName: "Deleted", + type: { + name: "Boolean" + } + }, + snapshot: { + serializedName: "Snapshot", + required: true, + xmlName: "Snapshot", + type: { + name: "String" + } + }, + versionId: { + serializedName: "VersionId", + xmlName: "VersionId", + type: { + name: "String" + } + }, + isCurrentVersion: { + serializedName: "IsCurrentVersion", + xmlName: "IsCurrentVersion", + type: { + name: "Boolean" + } + }, + properties: { + serializedName: "Properties", + xmlName: "Properties", + type: { + name: "Composite", + className: "BlobPropertiesInternal" + } + }, + metadata: { + serializedName: "Metadata", + xmlName: "Metadata", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + blobTags: { + serializedName: "BlobTags", + xmlName: "Tags", + type: { + name: "Composite", + className: "BlobTags" + } + }, + objectReplicationMetadata: { + serializedName: "ObjectReplicationMetadata", + xmlName: "OrMetadata", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + hasVersionsOnly: { + serializedName: "HasVersionsOnly", + xmlName: "HasVersionsOnly", + type: { + name: "Boolean" + } + } + } + } + }; + var BlobName = { + serializedName: "BlobName", + type: { + name: "Composite", + className: "BlobName", + modelProperties: { + encoded: { + serializedName: "Encoded", + xmlName: "Encoded", + xmlIsAttribute: true, + type: { + name: "Boolean" + } + }, + content: { + serializedName: "content", + xmlName: "content", + xmlIsMsText: true, + type: { + name: "String" + } + } + } + } + }; + var BlobPropertiesInternal = { + serializedName: "BlobPropertiesInternal", + xmlName: "Properties", + type: { + name: "Composite", + className: "BlobPropertiesInternal", + modelProperties: { + createdOn: { + serializedName: "Creation-Time", + xmlName: "Creation-Time", + type: { + name: "DateTimeRfc1123" + } + }, + lastModified: { + serializedName: "Last-Modified", + required: true, + xmlName: "Last-Modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "Etag", + required: true, + xmlName: "Etag", + type: { + name: "String" + } + }, + contentLength: { + serializedName: "Content-Length", + xmlName: "Content-Length", + type: { + name: "Number" + } + }, + contentType: { + serializedName: "Content-Type", + xmlName: "Content-Type", + type: { + name: "String" + } + }, + contentEncoding: { + serializedName: "Content-Encoding", + xmlName: "Content-Encoding", + type: { + name: "String" + } + }, + contentLanguage: { + serializedName: "Content-Language", + xmlName: "Content-Language", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "Content-MD5", + xmlName: "Content-MD5", + type: { + name: "ByteArray" + } + }, + contentDisposition: { + serializedName: "Content-Disposition", + xmlName: "Content-Disposition", + type: { + name: "String" + } + }, + cacheControl: { + serializedName: "Cache-Control", + xmlName: "Cache-Control", + type: { + name: "String" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + blobType: { + serializedName: "BlobType", + xmlName: "BlobType", + type: { + name: "Enum", + allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] + } + }, + leaseStatus: { + serializedName: "LeaseStatus", + xmlName: "LeaseStatus", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + leaseState: { + serializedName: "LeaseState", + xmlName: "LeaseState", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseDuration: { + serializedName: "LeaseDuration", + xmlName: "LeaseDuration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + copyId: { + serializedName: "CopyId", + xmlName: "CopyId", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "CopyStatus", + xmlName: "CopyStatus", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + copySource: { + serializedName: "CopySource", + xmlName: "CopySource", + type: { + name: "String" + } + }, + copyProgress: { + serializedName: "CopyProgress", + xmlName: "CopyProgress", + type: { + name: "String" + } + }, + copyCompletedOn: { + serializedName: "CopyCompletionTime", + xmlName: "CopyCompletionTime", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + serializedName: "CopyStatusDescription", + xmlName: "CopyStatusDescription", + type: { + name: "String" + } + }, + serverEncrypted: { + serializedName: "ServerEncrypted", + xmlName: "ServerEncrypted", + type: { + name: "Boolean" + } + }, + incrementalCopy: { + serializedName: "IncrementalCopy", + xmlName: "IncrementalCopy", + type: { + name: "Boolean" + } + }, + destinationSnapshot: { + serializedName: "DestinationSnapshot", + xmlName: "DestinationSnapshot", + type: { + name: "String" + } + }, + deletedOn: { + serializedName: "DeletedTime", + xmlName: "DeletedTime", + type: { + name: "DateTimeRfc1123" + } + }, + remainingRetentionDays: { + serializedName: "RemainingRetentionDays", + xmlName: "RemainingRetentionDays", + type: { + name: "Number" + } + }, + accessTier: { + serializedName: "AccessTier", + xmlName: "AccessTier", + type: { + name: "Enum", + allowedValues: [ + "P4", + "P6", + "P10", + "P15", + "P20", + "P30", + "P40", + "P50", + "P60", + "P70", + "P80", + "Hot", + "Cool", + "Archive", + "Cold" + ] + } + }, + accessTierInferred: { + serializedName: "AccessTierInferred", + xmlName: "AccessTierInferred", + type: { + name: "Boolean" + } + }, + archiveStatus: { + serializedName: "ArchiveStatus", + xmlName: "ArchiveStatus", + type: { + name: "Enum", + allowedValues: [ + "rehydrate-pending-to-hot", + "rehydrate-pending-to-cool", + "rehydrate-pending-to-cold" + ] + } + }, + customerProvidedKeySha256: { + serializedName: "CustomerProvidedKeySha256", + xmlName: "CustomerProvidedKeySha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "EncryptionScope", + xmlName: "EncryptionScope", + type: { + name: "String" + } + }, + accessTierChangedOn: { + serializedName: "AccessTierChangeTime", + xmlName: "AccessTierChangeTime", + type: { + name: "DateTimeRfc1123" + } + }, + tagCount: { + serializedName: "TagCount", + xmlName: "TagCount", + type: { + name: "Number" + } + }, + expiresOn: { + serializedName: "Expiry-Time", + xmlName: "Expiry-Time", + type: { + name: "DateTimeRfc1123" + } + }, + isSealed: { + serializedName: "Sealed", + xmlName: "Sealed", + type: { + name: "Boolean" + } + }, + rehydratePriority: { + serializedName: "RehydratePriority", + xmlName: "RehydratePriority", + type: { + name: "Enum", + allowedValues: ["High", "Standard"] + } + }, + lastAccessedOn: { + serializedName: "LastAccessTime", + xmlName: "LastAccessTime", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyExpiresOn: { + serializedName: "ImmutabilityPolicyUntilDate", + xmlName: "ImmutabilityPolicyUntilDate", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "ImmutabilityPolicyMode", + xmlName: "ImmutabilityPolicyMode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "LegalHold", + xmlName: "LegalHold", + type: { + name: "Boolean" + } + } + } + } + }; + var ListBlobsHierarchySegmentResponse = { + serializedName: "ListBlobsHierarchySegmentResponse", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "ListBlobsHierarchySegmentResponse", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + containerName: { + serializedName: "ContainerName", + required: true, + xmlName: "ContainerName", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + prefix: { + serializedName: "Prefix", + xmlName: "Prefix", + type: { + name: "String" + } + }, + marker: { + serializedName: "Marker", + xmlName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + serializedName: "MaxResults", + xmlName: "MaxResults", + type: { + name: "Number" + } + }, + delimiter: { + serializedName: "Delimiter", + xmlName: "Delimiter", + type: { + name: "String" + } + }, + segment: { + serializedName: "Segment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobHierarchyListSegment" + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } + } + }; + var BlobHierarchyListSegment = { + serializedName: "BlobHierarchyListSegment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobHierarchyListSegment", + modelProperties: { + blobPrefixes: { + serializedName: "BlobPrefixes", + xmlName: "BlobPrefixes", + xmlElementName: "BlobPrefix", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobPrefix" + } + } + } + }, + blobItems: { + serializedName: "BlobItems", + required: true, + xmlName: "BlobItems", + xmlElementName: "Blob", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobItemInternal" + } + } + } + } + } + } + }; + var BlobPrefix = { + serializedName: "BlobPrefix", + type: { + name: "Composite", + className: "BlobPrefix", + modelProperties: { + name: { + serializedName: "Name", + xmlName: "Name", + type: { + name: "Composite", + className: "BlobName" + } + } + } + } + }; + var BlockLookupList = { + serializedName: "BlockLookupList", + xmlName: "BlockList", + type: { + name: "Composite", + className: "BlockLookupList", + modelProperties: { + committed: { + serializedName: "Committed", + xmlName: "Committed", + xmlElementName: "Committed", + type: { + name: "Sequence", + element: { + type: { + name: "String" + } + } + } + }, + uncommitted: { + serializedName: "Uncommitted", + xmlName: "Uncommitted", + xmlElementName: "Uncommitted", + type: { + name: "Sequence", + element: { + type: { + name: "String" + } + } + } + }, + latest: { + serializedName: "Latest", + xmlName: "Latest", + xmlElementName: "Latest", + type: { + name: "Sequence", + element: { + type: { + name: "String" + } + } + } + } + } + } + }; + var BlockList = { + serializedName: "BlockList", + type: { + name: "Composite", + className: "BlockList", + modelProperties: { + committedBlocks: { + serializedName: "CommittedBlocks", + xmlName: "CommittedBlocks", + xmlIsWrapped: true, + xmlElementName: "Block", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "Block" + } + } + } + }, + uncommittedBlocks: { + serializedName: "UncommittedBlocks", + xmlName: "UncommittedBlocks", + xmlIsWrapped: true, + xmlElementName: "Block", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "Block" + } + } + } + } + } + } + }; + var Block = { + serializedName: "Block", + type: { + name: "Composite", + className: "Block", + modelProperties: { + name: { + serializedName: "Name", + required: true, + xmlName: "Name", + type: { + name: "String" + } + }, + size: { + serializedName: "Size", + required: true, + xmlName: "Size", + type: { + name: "Number" + } + } + } + } + }; + var PageList = { + serializedName: "PageList", + type: { + name: "Composite", + className: "PageList", + modelProperties: { + pageRange: { + serializedName: "PageRange", + xmlName: "PageRange", + xmlElementName: "PageRange", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "PageRange" + } + } + } + }, + clearRange: { + serializedName: "ClearRange", + xmlName: "ClearRange", + xmlElementName: "ClearRange", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ClearRange" + } + } + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } + } + }; + var PageRange = { + serializedName: "PageRange", + xmlName: "PageRange", + type: { + name: "Composite", + className: "PageRange", + modelProperties: { + start: { + serializedName: "Start", + required: true, + xmlName: "Start", + type: { + name: "Number" + } + }, + end: { + serializedName: "End", + required: true, + xmlName: "End", + type: { + name: "Number" + } + } + } + } + }; + var ClearRange = { + serializedName: "ClearRange", + xmlName: "ClearRange", + type: { + name: "Composite", + className: "ClearRange", + modelProperties: { + start: { + serializedName: "Start", + required: true, + xmlName: "Start", + type: { + name: "Number" + } + }, + end: { + serializedName: "End", + required: true, + xmlName: "End", + type: { + name: "Number" + } + } + } + } + }; + var QueryRequest = { + serializedName: "QueryRequest", + xmlName: "QueryRequest", + type: { + name: "Composite", + className: "QueryRequest", + modelProperties: { + queryType: { + serializedName: "QueryType", + required: true, + xmlName: "QueryType", + type: { + name: "String" + } + }, + expression: { + serializedName: "Expression", + required: true, + xmlName: "Expression", + type: { + name: "String" + } + }, + inputSerialization: { + serializedName: "InputSerialization", + xmlName: "InputSerialization", + type: { + name: "Composite", + className: "QuerySerialization" + } + }, + outputSerialization: { + serializedName: "OutputSerialization", + xmlName: "OutputSerialization", + type: { + name: "Composite", + className: "QuerySerialization" + } + } + } + } + }; + var QuerySerialization = { + serializedName: "QuerySerialization", + type: { + name: "Composite", + className: "QuerySerialization", + modelProperties: { + format: { + serializedName: "Format", + xmlName: "Format", + type: { + name: "Composite", + className: "QueryFormat" + } + } + } + } + }; + var QueryFormat = { + serializedName: "QueryFormat", + type: { + name: "Composite", + className: "QueryFormat", + modelProperties: { + type: { + serializedName: "Type", + required: true, + xmlName: "Type", + type: { + name: "Enum", + allowedValues: ["delimited", "json", "arrow", "parquet"] + } + }, + delimitedTextConfiguration: { + serializedName: "DelimitedTextConfiguration", + xmlName: "DelimitedTextConfiguration", + type: { + name: "Composite", + className: "DelimitedTextConfiguration" + } + }, + jsonTextConfiguration: { + serializedName: "JsonTextConfiguration", + xmlName: "JsonTextConfiguration", + type: { + name: "Composite", + className: "JsonTextConfiguration" + } + }, + arrowConfiguration: { + serializedName: "ArrowConfiguration", + xmlName: "ArrowConfiguration", + type: { + name: "Composite", + className: "ArrowConfiguration" + } + }, + parquetTextConfiguration: { + serializedName: "ParquetTextConfiguration", + xmlName: "ParquetTextConfiguration", + type: { + name: "Dictionary", + value: { type: { name: "any" } } + } + } + } + } + }; + var DelimitedTextConfiguration = { + serializedName: "DelimitedTextConfiguration", + xmlName: "DelimitedTextConfiguration", + type: { + name: "Composite", + className: "DelimitedTextConfiguration", + modelProperties: { + columnSeparator: { + serializedName: "ColumnSeparator", + xmlName: "ColumnSeparator", + type: { + name: "String" + } + }, + fieldQuote: { + serializedName: "FieldQuote", + xmlName: "FieldQuote", + type: { + name: "String" + } + }, + recordSeparator: { + serializedName: "RecordSeparator", + xmlName: "RecordSeparator", + type: { + name: "String" + } + }, + escapeChar: { + serializedName: "EscapeChar", + xmlName: "EscapeChar", + type: { + name: "String" + } + }, + headersPresent: { + serializedName: "HeadersPresent", + xmlName: "HasHeaders", + type: { + name: "Boolean" + } + } + } + } + }; + var JsonTextConfiguration = { + serializedName: "JsonTextConfiguration", + xmlName: "JsonTextConfiguration", + type: { + name: "Composite", + className: "JsonTextConfiguration", + modelProperties: { + recordSeparator: { + serializedName: "RecordSeparator", + xmlName: "RecordSeparator", + type: { + name: "String" + } + } + } + } + }; + var ArrowConfiguration = { + serializedName: "ArrowConfiguration", + xmlName: "ArrowConfiguration", + type: { + name: "Composite", + className: "ArrowConfiguration", + modelProperties: { + schema: { + serializedName: "Schema", + required: true, + xmlName: "Schema", + xmlIsWrapped: true, + xmlElementName: "Field", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ArrowField" + } + } + } + } + } + } + }; + var ArrowField = { + serializedName: "ArrowField", + xmlName: "Field", + type: { + name: "Composite", + className: "ArrowField", + modelProperties: { + type: { + serializedName: "Type", + required: true, + xmlName: "Type", + type: { + name: "String" + } + }, + name: { + serializedName: "Name", + xmlName: "Name", + type: { + name: "String" + } + }, + precision: { + serializedName: "Precision", + xmlName: "Precision", + type: { + name: "Number" + } + }, + scale: { + serializedName: "Scale", + xmlName: "Scale", + type: { + name: "Number" + } + } + } + } + }; + var ServiceSetPropertiesHeaders = { + serializedName: "Service_setPropertiesHeaders", + type: { + name: "Composite", + className: "ServiceSetPropertiesHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceSetPropertiesExceptionHeaders = { + serializedName: "Service_setPropertiesExceptionHeaders", + type: { + name: "Composite", + className: "ServiceSetPropertiesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetPropertiesHeaders = { + serializedName: "Service_getPropertiesHeaders", + type: { + name: "Composite", + className: "ServiceGetPropertiesHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetPropertiesExceptionHeaders = { + serializedName: "Service_getPropertiesExceptionHeaders", + type: { + name: "Composite", + className: "ServiceGetPropertiesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetStatisticsHeaders = { + serializedName: "Service_getStatisticsHeaders", + type: { + name: "Composite", + className: "ServiceGetStatisticsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetStatisticsExceptionHeaders = { + serializedName: "Service_getStatisticsExceptionHeaders", + type: { + name: "Composite", + className: "ServiceGetStatisticsExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceListContainersSegmentHeaders = { + serializedName: "Service_listContainersSegmentHeaders", + type: { + name: "Composite", + className: "ServiceListContainersSegmentHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceListContainersSegmentExceptionHeaders = { + serializedName: "Service_listContainersSegmentExceptionHeaders", + type: { + name: "Composite", + className: "ServiceListContainersSegmentExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetUserDelegationKeyHeaders = { + serializedName: "Service_getUserDelegationKeyHeaders", + type: { + name: "Composite", + className: "ServiceGetUserDelegationKeyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetUserDelegationKeyExceptionHeaders = { + serializedName: "Service_getUserDelegationKeyExceptionHeaders", + type: { + name: "Composite", + className: "ServiceGetUserDelegationKeyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetAccountInfoHeaders = { + serializedName: "Service_getAccountInfoHeaders", + type: { + name: "Composite", + className: "ServiceGetAccountInfoHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + skuName: { + serializedName: "x-ms-sku-name", + xmlName: "x-ms-sku-name", + type: { + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS" + ] + } + }, + accountKind: { + serializedName: "x-ms-account-kind", + xmlName: "x-ms-account-kind", + type: { + name: "Enum", + allowedValues: [ + "Storage", + "BlobStorage", + "StorageV2", + "FileStorage", + "BlockBlobStorage" + ] + } + }, + isHierarchicalNamespaceEnabled: { + serializedName: "x-ms-is-hns-enabled", + xmlName: "x-ms-is-hns-enabled", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceGetAccountInfoExceptionHeaders = { + serializedName: "Service_getAccountInfoExceptionHeaders", + type: { + name: "Composite", + className: "ServiceGetAccountInfoExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceSubmitBatchHeaders = { + serializedName: "Service_submitBatchHeaders", + type: { + name: "Composite", + className: "ServiceSubmitBatchHeaders", + modelProperties: { + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceSubmitBatchExceptionHeaders = { + serializedName: "Service_submitBatchExceptionHeaders", + type: { + name: "Composite", + className: "ServiceSubmitBatchExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceFilterBlobsHeaders = { + serializedName: "Service_filterBlobsHeaders", + type: { + name: "Composite", + className: "ServiceFilterBlobsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ServiceFilterBlobsExceptionHeaders = { + serializedName: "Service_filterBlobsExceptionHeaders", + type: { + name: "Composite", + className: "ServiceFilterBlobsExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerCreateHeaders = { + serializedName: "Container_createHeaders", + type: { + name: "Composite", + className: "ContainerCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerCreateExceptionHeaders = { + serializedName: "Container_createExceptionHeaders", + type: { + name: "Composite", + className: "ContainerCreateExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerGetPropertiesHeaders = { + serializedName: "Container_getPropertiesHeaders", + type: { + name: "Composite", + className: "ContainerGetPropertiesHeaders", + modelProperties: { + metadata: { + serializedName: "x-ms-meta", + headerCollectionPrefix: "x-ms-meta-", + xmlName: "x-ms-meta", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + xmlName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + xmlName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + xmlName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobPublicAccess: { + serializedName: "x-ms-blob-public-access", + xmlName: "x-ms-blob-public-access", + type: { + name: "Enum", + allowedValues: ["container", "blob"] + } + }, + hasImmutabilityPolicy: { + serializedName: "x-ms-has-immutability-policy", + xmlName: "x-ms-has-immutability-policy", + type: { + name: "Boolean" + } + }, + hasLegalHold: { + serializedName: "x-ms-has-legal-hold", + xmlName: "x-ms-has-legal-hold", + type: { + name: "Boolean" + } + }, + defaultEncryptionScope: { + serializedName: "x-ms-default-encryption-scope", + xmlName: "x-ms-default-encryption-scope", + type: { + name: "String" + } + }, + denyEncryptionScopeOverride: { + serializedName: "x-ms-deny-encryption-scope-override", + xmlName: "x-ms-deny-encryption-scope-override", + type: { + name: "Boolean" + } + }, + isImmutableStorageWithVersioningEnabled: { + serializedName: "x-ms-immutable-storage-with-versioning-enabled", + xmlName: "x-ms-immutable-storage-with-versioning-enabled", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerGetPropertiesExceptionHeaders = { + serializedName: "Container_getPropertiesExceptionHeaders", + type: { + name: "Composite", + className: "ContainerGetPropertiesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerDeleteHeaders = { + serializedName: "Container_deleteHeaders", + type: { + name: "Composite", + className: "ContainerDeleteHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerDeleteExceptionHeaders = { + serializedName: "Container_deleteExceptionHeaders", + type: { + name: "Composite", + className: "ContainerDeleteExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerSetMetadataHeaders = { + serializedName: "Container_setMetadataHeaders", + type: { + name: "Composite", + className: "ContainerSetMetadataHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerSetMetadataExceptionHeaders = { + serializedName: "Container_setMetadataExceptionHeaders", + type: { + name: "Composite", + className: "ContainerSetMetadataExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerGetAccessPolicyHeaders = { + serializedName: "Container_getAccessPolicyHeaders", + type: { + name: "Composite", + className: "ContainerGetAccessPolicyHeaders", + modelProperties: { + blobPublicAccess: { + serializedName: "x-ms-blob-public-access", + xmlName: "x-ms-blob-public-access", + type: { + name: "Enum", + allowedValues: ["container", "blob"] + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerGetAccessPolicyExceptionHeaders = { + serializedName: "Container_getAccessPolicyExceptionHeaders", + type: { + name: "Composite", + className: "ContainerGetAccessPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerSetAccessPolicyHeaders = { + serializedName: "Container_setAccessPolicyHeaders", + type: { + name: "Composite", + className: "ContainerSetAccessPolicyHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerSetAccessPolicyExceptionHeaders = { + serializedName: "Container_setAccessPolicyExceptionHeaders", + type: { + name: "Composite", + className: "ContainerSetAccessPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerRestoreHeaders = { + serializedName: "Container_restoreHeaders", + type: { + name: "Composite", + className: "ContainerRestoreHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerRestoreExceptionHeaders = { + serializedName: "Container_restoreExceptionHeaders", + type: { + name: "Composite", + className: "ContainerRestoreExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerRenameHeaders = { + serializedName: "Container_renameHeaders", + type: { + name: "Composite", + className: "ContainerRenameHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerRenameExceptionHeaders = { + serializedName: "Container_renameExceptionHeaders", + type: { + name: "Composite", + className: "ContainerRenameExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerSubmitBatchHeaders = { + serializedName: "Container_submitBatchHeaders", + type: { + name: "Composite", + className: "ContainerSubmitBatchHeaders", + modelProperties: { + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + } + } + } + }; + var ContainerSubmitBatchExceptionHeaders = { + serializedName: "Container_submitBatchExceptionHeaders", + type: { + name: "Composite", + className: "ContainerSubmitBatchExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerFilterBlobsHeaders = { + serializedName: "Container_filterBlobsHeaders", + type: { + name: "Composite", + className: "ContainerFilterBlobsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var ContainerFilterBlobsExceptionHeaders = { + serializedName: "Container_filterBlobsExceptionHeaders", + type: { + name: "Composite", + className: "ContainerFilterBlobsExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerAcquireLeaseHeaders = { + serializedName: "Container_acquireLeaseHeaders", + type: { + name: "Composite", + className: "ContainerAcquireLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var ContainerAcquireLeaseExceptionHeaders = { + serializedName: "Container_acquireLeaseExceptionHeaders", + type: { + name: "Composite", + className: "ContainerAcquireLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerReleaseLeaseHeaders = { + serializedName: "Container_releaseLeaseHeaders", + type: { + name: "Composite", + className: "ContainerReleaseLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var ContainerReleaseLeaseExceptionHeaders = { + serializedName: "Container_releaseLeaseExceptionHeaders", + type: { + name: "Composite", + className: "ContainerReleaseLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerRenewLeaseHeaders = { + serializedName: "Container_renewLeaseHeaders", + type: { + name: "Composite", + className: "ContainerRenewLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var ContainerRenewLeaseExceptionHeaders = { + serializedName: "Container_renewLeaseExceptionHeaders", + type: { + name: "Composite", + className: "ContainerRenewLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerBreakLeaseHeaders = { + serializedName: "Container_breakLeaseHeaders", + type: { + name: "Composite", + className: "ContainerBreakLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseTime: { + serializedName: "x-ms-lease-time", + xmlName: "x-ms-lease-time", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var ContainerBreakLeaseExceptionHeaders = { + serializedName: "Container_breakLeaseExceptionHeaders", + type: { + name: "Composite", + className: "ContainerBreakLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerChangeLeaseHeaders = { + serializedName: "Container_changeLeaseHeaders", + type: { + name: "Composite", + className: "ContainerChangeLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var ContainerChangeLeaseExceptionHeaders = { + serializedName: "Container_changeLeaseExceptionHeaders", + type: { + name: "Composite", + className: "ContainerChangeLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerListBlobFlatSegmentHeaders = { + serializedName: "Container_listBlobFlatSegmentHeaders", + type: { + name: "Composite", + className: "ContainerListBlobFlatSegmentHeaders", + modelProperties: { + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerListBlobFlatSegmentExceptionHeaders = { + serializedName: "Container_listBlobFlatSegmentExceptionHeaders", + type: { + name: "Composite", + className: "ContainerListBlobFlatSegmentExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerListBlobHierarchySegmentHeaders = { + serializedName: "Container_listBlobHierarchySegmentHeaders", + type: { + name: "Composite", + className: "ContainerListBlobHierarchySegmentHeaders", + modelProperties: { + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerListBlobHierarchySegmentExceptionHeaders = { + serializedName: "Container_listBlobHierarchySegmentExceptionHeaders", + type: { + name: "Composite", + className: "ContainerListBlobHierarchySegmentExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var ContainerGetAccountInfoHeaders = { + serializedName: "Container_getAccountInfoHeaders", + type: { + name: "Composite", + className: "ContainerGetAccountInfoHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + skuName: { + serializedName: "x-ms-sku-name", + xmlName: "x-ms-sku-name", + type: { + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS" + ] + } + }, + accountKind: { + serializedName: "x-ms-account-kind", + xmlName: "x-ms-account-kind", + type: { + name: "Enum", + allowedValues: [ + "Storage", + "BlobStorage", + "StorageV2", + "FileStorage", + "BlockBlobStorage" + ] + } + }, + isHierarchicalNamespaceEnabled: { + serializedName: "x-ms-is-hns-enabled", + xmlName: "x-ms-is-hns-enabled", + type: { + name: "Boolean" + } + } + } + } + }; + var ContainerGetAccountInfoExceptionHeaders = { + serializedName: "Container_getAccountInfoExceptionHeaders", + type: { + name: "Composite", + className: "ContainerGetAccountInfoExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobDownloadHeaders = { + serializedName: "Blob_downloadHeaders", + type: { + name: "Composite", + className: "BlobDownloadHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + createdOn: { + serializedName: "x-ms-creation-time", + xmlName: "x-ms-creation-time", + type: { + name: "DateTimeRfc1123" + } + }, + metadata: { + serializedName: "x-ms-meta", + headerCollectionPrefix: "x-ms-meta-", + xmlName: "x-ms-meta", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + objectReplicationPolicyId: { + serializedName: "x-ms-or-policy-id", + xmlName: "x-ms-or-policy-id", + type: { + name: "String" + } + }, + objectReplicationRules: { + serializedName: "x-ms-or", + headerCollectionPrefix: "x-ms-or-", + xmlName: "x-ms-or", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + contentLength: { + serializedName: "content-length", + xmlName: "content-length", + type: { + name: "Number" + } + }, + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + contentRange: { + serializedName: "content-range", + xmlName: "content-range", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + contentEncoding: { + serializedName: "content-encoding", + xmlName: "content-encoding", + type: { + name: "String" + } + }, + cacheControl: { + serializedName: "cache-control", + xmlName: "cache-control", + type: { + name: "String" + } + }, + contentDisposition: { + serializedName: "content-disposition", + xmlName: "content-disposition", + type: { + name: "String" + } + }, + contentLanguage: { + serializedName: "content-language", + xmlName: "content-language", + type: { + name: "String" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + blobType: { + serializedName: "x-ms-blob-type", + xmlName: "x-ms-blob-type", + type: { + name: "Enum", + allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] + } + }, + copyCompletedOn: { + serializedName: "x-ms-copy-completion-time", + xmlName: "x-ms-copy-completion-time", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + serializedName: "x-ms-copy-status-description", + xmlName: "x-ms-copy-status-description", + type: { + name: "String" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyProgress: { + serializedName: "x-ms-copy-progress", + xmlName: "x-ms-copy-progress", + type: { + name: "String" + } + }, + copySource: { + serializedName: "x-ms-copy-source", + xmlName: "x-ms-copy-source", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + xmlName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + xmlName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + xmlName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + xmlName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + isCurrentVersion: { + serializedName: "x-ms-is-current-version", + xmlName: "x-ms-is-current-version", + type: { + name: "Boolean" + } + }, + acceptRanges: { + serializedName: "accept-ranges", + xmlName: "accept-ranges", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + xmlName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-server-encrypted", + xmlName: "x-ms-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + blobContentMD5: { + serializedName: "x-ms-blob-content-md5", + xmlName: "x-ms-blob-content-md5", + type: { + name: "ByteArray" + } + }, + tagCount: { + serializedName: "x-ms-tag-count", + xmlName: "x-ms-tag-count", + type: { + name: "Number" + } + }, + isSealed: { + serializedName: "x-ms-blob-sealed", + xmlName: "x-ms-blob-sealed", + type: { + name: "Boolean" + } + }, + lastAccessed: { + serializedName: "x-ms-last-access-time", + xmlName: "x-ms-last-access-time", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyExpiresOn: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + } + } + } + }; + var BlobDownloadExceptionHeaders = { + serializedName: "Blob_downloadExceptionHeaders", + type: { + name: "Composite", + className: "BlobDownloadExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobGetPropertiesHeaders = { + serializedName: "Blob_getPropertiesHeaders", + type: { + name: "Composite", + className: "BlobGetPropertiesHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + createdOn: { + serializedName: "x-ms-creation-time", + xmlName: "x-ms-creation-time", + type: { + name: "DateTimeRfc1123" + } + }, + metadata: { + serializedName: "x-ms-meta", + headerCollectionPrefix: "x-ms-meta-", + xmlName: "x-ms-meta", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + objectReplicationPolicyId: { + serializedName: "x-ms-or-policy-id", + xmlName: "x-ms-or-policy-id", + type: { + name: "String" + } + }, + objectReplicationRules: { + serializedName: "x-ms-or", + headerCollectionPrefix: "x-ms-or-", + xmlName: "x-ms-or", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + blobType: { + serializedName: "x-ms-blob-type", + xmlName: "x-ms-blob-type", + type: { + name: "Enum", + allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] + } + }, + copyCompletedOn: { + serializedName: "x-ms-copy-completion-time", + xmlName: "x-ms-copy-completion-time", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + serializedName: "x-ms-copy-status-description", + xmlName: "x-ms-copy-status-description", + type: { + name: "String" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyProgress: { + serializedName: "x-ms-copy-progress", + xmlName: "x-ms-copy-progress", + type: { + name: "String" + } + }, + copySource: { + serializedName: "x-ms-copy-source", + xmlName: "x-ms-copy-source", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + xmlName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + isIncrementalCopy: { + serializedName: "x-ms-incremental-copy", + xmlName: "x-ms-incremental-copy", + type: { + name: "Boolean" + } + }, + destinationSnapshot: { + serializedName: "x-ms-copy-destination-snapshot", + xmlName: "x-ms-copy-destination-snapshot", + type: { + name: "String" + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + xmlName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + xmlName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + xmlName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + contentLength: { + serializedName: "content-length", + xmlName: "content-length", + type: { + name: "Number" + } + }, + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + contentEncoding: { + serializedName: "content-encoding", + xmlName: "content-encoding", + type: { + name: "String" + } + }, + contentDisposition: { + serializedName: "content-disposition", + xmlName: "content-disposition", + type: { + name: "String" + } + }, + contentLanguage: { + serializedName: "content-language", + xmlName: "content-language", + type: { + name: "String" + } + }, + cacheControl: { + serializedName: "cache-control", + xmlName: "cache-control", + type: { + name: "String" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + acceptRanges: { + serializedName: "accept-ranges", + xmlName: "accept-ranges", + type: { + name: "String" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + xmlName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-server-encrypted", + xmlName: "x-ms-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + accessTier: { + serializedName: "x-ms-access-tier", + xmlName: "x-ms-access-tier", + type: { + name: "String" + } + }, + accessTierInferred: { + serializedName: "x-ms-access-tier-inferred", + xmlName: "x-ms-access-tier-inferred", + type: { + name: "Boolean" + } + }, + archiveStatus: { + serializedName: "x-ms-archive-status", + xmlName: "x-ms-archive-status", + type: { + name: "String" + } + }, + accessTierChangedOn: { + serializedName: "x-ms-access-tier-change-time", + xmlName: "x-ms-access-tier-change-time", + type: { + name: "DateTimeRfc1123" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + isCurrentVersion: { + serializedName: "x-ms-is-current-version", + xmlName: "x-ms-is-current-version", + type: { + name: "Boolean" + } + }, + tagCount: { + serializedName: "x-ms-tag-count", + xmlName: "x-ms-tag-count", + type: { + name: "Number" + } + }, + expiresOn: { + serializedName: "x-ms-expiry-time", + xmlName: "x-ms-expiry-time", + type: { + name: "DateTimeRfc1123" + } + }, + isSealed: { + serializedName: "x-ms-blob-sealed", + xmlName: "x-ms-blob-sealed", + type: { + name: "Boolean" + } + }, + rehydratePriority: { + serializedName: "x-ms-rehydrate-priority", + xmlName: "x-ms-rehydrate-priority", + type: { + name: "Enum", + allowedValues: ["High", "Standard"] + } + }, + lastAccessed: { + serializedName: "x-ms-last-access-time", + xmlName: "x-ms-last-access-time", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyExpiresOn: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobGetPropertiesExceptionHeaders = { + serializedName: "Blob_getPropertiesExceptionHeaders", + type: { + name: "Composite", + className: "BlobGetPropertiesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobDeleteHeaders = { + serializedName: "Blob_deleteHeaders", + type: { + name: "Composite", + className: "BlobDeleteHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobDeleteExceptionHeaders = { + serializedName: "Blob_deleteExceptionHeaders", + type: { + name: "Composite", + className: "BlobDeleteExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobUndeleteHeaders = { + serializedName: "Blob_undeleteHeaders", + type: { + name: "Composite", + className: "BlobUndeleteHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobUndeleteExceptionHeaders = { + serializedName: "Blob_undeleteExceptionHeaders", + type: { + name: "Composite", + className: "BlobUndeleteExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetExpiryHeaders = { + serializedName: "Blob_setExpiryHeaders", + type: { + name: "Composite", + className: "BlobSetExpiryHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobSetExpiryExceptionHeaders = { + serializedName: "Blob_setExpiryExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetExpiryExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetHttpHeadersHeaders = { + serializedName: "Blob_setHttpHeadersHeaders", + type: { + name: "Composite", + className: "BlobSetHttpHeadersHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetHttpHeadersExceptionHeaders = { + serializedName: "Blob_setHttpHeadersExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetHttpHeadersExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetImmutabilityPolicyHeaders = { + serializedName: "Blob_setImmutabilityPolicyHeaders", + type: { + name: "Composite", + className: "BlobSetImmutabilityPolicyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyExpiry: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + } + } + } + }; + var BlobSetImmutabilityPolicyExceptionHeaders = { + serializedName: "Blob_setImmutabilityPolicyExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetImmutabilityPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobDeleteImmutabilityPolicyHeaders = { + serializedName: "Blob_deleteImmutabilityPolicyHeaders", + type: { + name: "Composite", + className: "BlobDeleteImmutabilityPolicyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobDeleteImmutabilityPolicyExceptionHeaders = { + serializedName: "Blob_deleteImmutabilityPolicyExceptionHeaders", + type: { + name: "Composite", + className: "BlobDeleteImmutabilityPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetLegalHoldHeaders = { + serializedName: "Blob_setLegalHoldHeaders", + type: { + name: "Composite", + className: "BlobSetLegalHoldHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } + } + } + }; + var BlobSetLegalHoldExceptionHeaders = { + serializedName: "Blob_setLegalHoldExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetLegalHoldExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetMetadataHeaders = { + serializedName: "Blob_setMetadataHeaders", + type: { + name: "Composite", + className: "BlobSetMetadataHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetMetadataExceptionHeaders = { + serializedName: "Blob_setMetadataExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetMetadataExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobAcquireLeaseHeaders = { + serializedName: "Blob_acquireLeaseHeaders", + type: { + name: "Composite", + className: "BlobAcquireLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobAcquireLeaseExceptionHeaders = { + serializedName: "Blob_acquireLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobAcquireLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobReleaseLeaseHeaders = { + serializedName: "Blob_releaseLeaseHeaders", + type: { + name: "Composite", + className: "BlobReleaseLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobReleaseLeaseExceptionHeaders = { + serializedName: "Blob_releaseLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobReleaseLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobRenewLeaseHeaders = { + serializedName: "Blob_renewLeaseHeaders", + type: { + name: "Composite", + className: "BlobRenewLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobRenewLeaseExceptionHeaders = { + serializedName: "Blob_renewLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobRenewLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobChangeLeaseHeaders = { + serializedName: "Blob_changeLeaseHeaders", + type: { + name: "Composite", + className: "BlobChangeLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobChangeLeaseExceptionHeaders = { + serializedName: "Blob_changeLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobChangeLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobBreakLeaseHeaders = { + serializedName: "Blob_breakLeaseHeaders", + type: { + name: "Composite", + className: "BlobBreakLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseTime: { + serializedName: "x-ms-lease-time", + xmlName: "x-ms-lease-time", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var BlobBreakLeaseExceptionHeaders = { + serializedName: "Blob_breakLeaseExceptionHeaders", + type: { + name: "Composite", + className: "BlobBreakLeaseExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobCreateSnapshotHeaders = { + serializedName: "Blob_createSnapshotHeaders", + type: { + name: "Composite", + className: "BlobCreateSnapshotHeaders", + modelProperties: { + snapshot: { + serializedName: "x-ms-snapshot", + xmlName: "x-ms-snapshot", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobCreateSnapshotExceptionHeaders = { + serializedName: "Blob_createSnapshotExceptionHeaders", + type: { + name: "Composite", + className: "BlobCreateSnapshotExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobStartCopyFromURLHeaders = { + serializedName: "Blob_startCopyFromURLHeaders", + type: { + name: "Composite", + className: "BlobStartCopyFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + xmlName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobStartCopyFromURLExceptionHeaders = { + serializedName: "Blob_startCopyFromURLExceptionHeaders", + type: { + name: "Composite", + className: "BlobStartCopyFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobCopyFromURLHeaders = { + serializedName: "Blob_copyFromURLHeaders", + type: { + name: "Composite", + className: "BlobCopyFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + defaultValue: "success", + isConstant: true, + serializedName: "x-ms-copy-status", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobCopyFromURLExceptionHeaders = { + serializedName: "Blob_copyFromURLExceptionHeaders", + type: { + name: "Composite", + className: "BlobCopyFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobAbortCopyFromURLHeaders = { + serializedName: "Blob_abortCopyFromURLHeaders", + type: { + name: "Composite", + className: "BlobAbortCopyFromURLHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobAbortCopyFromURLExceptionHeaders = { + serializedName: "Blob_abortCopyFromURLExceptionHeaders", + type: { + name: "Composite", + className: "BlobAbortCopyFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetTierHeaders = { + serializedName: "Blob_setTierHeaders", + type: { + name: "Composite", + className: "BlobSetTierHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetTierExceptionHeaders = { + serializedName: "Blob_setTierExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetTierExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobGetAccountInfoHeaders = { + serializedName: "Blob_getAccountInfoHeaders", + type: { + name: "Composite", + className: "BlobGetAccountInfoHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + skuName: { + serializedName: "x-ms-sku-name", + xmlName: "x-ms-sku-name", + type: { + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS" + ] + } + }, + accountKind: { + serializedName: "x-ms-account-kind", + xmlName: "x-ms-account-kind", + type: { + name: "Enum", + allowedValues: [ + "Storage", + "BlobStorage", + "StorageV2", + "FileStorage", + "BlockBlobStorage" + ] + } + }, + isHierarchicalNamespaceEnabled: { + serializedName: "x-ms-is-hns-enabled", + xmlName: "x-ms-is-hns-enabled", + type: { + name: "Boolean" + } + } + } + } + }; + var BlobGetAccountInfoExceptionHeaders = { + serializedName: "Blob_getAccountInfoExceptionHeaders", + type: { + name: "Composite", + className: "BlobGetAccountInfoExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobQueryHeaders = { + serializedName: "Blob_queryHeaders", + type: { + name: "Composite", + className: "BlobQueryHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + metadata: { + serializedName: "x-ms-meta", + headerCollectionPrefix: "x-ms-meta-", + xmlName: "x-ms-meta", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + }, + contentLength: { + serializedName: "content-length", + xmlName: "content-length", + type: { + name: "Number" + } + }, + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + contentRange: { + serializedName: "content-range", + xmlName: "content-range", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + contentEncoding: { + serializedName: "content-encoding", + xmlName: "content-encoding", + type: { + name: "String" + } + }, + cacheControl: { + serializedName: "cache-control", + xmlName: "cache-control", + type: { + name: "String" + } + }, + contentDisposition: { + serializedName: "content-disposition", + xmlName: "content-disposition", + type: { + name: "String" + } + }, + contentLanguage: { + serializedName: "content-language", + xmlName: "content-language", + type: { + name: "String" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + blobType: { + serializedName: "x-ms-blob-type", + xmlName: "x-ms-blob-type", + type: { + name: "Enum", + allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] + } + }, + copyCompletionTime: { + serializedName: "x-ms-copy-completion-time", + xmlName: "x-ms-copy-completion-time", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + serializedName: "x-ms-copy-status-description", + xmlName: "x-ms-copy-status-description", + type: { + name: "String" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyProgress: { + serializedName: "x-ms-copy-progress", + xmlName: "x-ms-copy-progress", + type: { + name: "String" + } + }, + copySource: { + serializedName: "x-ms-copy-source", + xmlName: "x-ms-copy-source", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + xmlName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + xmlName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + xmlName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + xmlName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + acceptRanges: { + serializedName: "accept-ranges", + xmlName: "accept-ranges", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + xmlName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-server-encrypted", + xmlName: "x-ms-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + blobContentMD5: { + serializedName: "x-ms-blob-content-md5", + xmlName: "x-ms-blob-content-md5", + type: { + name: "ByteArray" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + } + } + } + }; + var BlobQueryExceptionHeaders = { + serializedName: "Blob_queryExceptionHeaders", + type: { + name: "Composite", + className: "BlobQueryExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobGetTagsHeaders = { + serializedName: "Blob_getTagsHeaders", + type: { + name: "Composite", + className: "BlobGetTagsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobGetTagsExceptionHeaders = { + serializedName: "Blob_getTagsExceptionHeaders", + type: { + name: "Composite", + className: "BlobGetTagsExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetTagsHeaders = { + serializedName: "Blob_setTagsHeaders", + type: { + name: "Composite", + className: "BlobSetTagsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlobSetTagsExceptionHeaders = { + serializedName: "Blob_setTagsExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetTagsExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobCreateHeaders = { + serializedName: "PageBlob_createHeaders", + type: { + name: "Composite", + className: "PageBlobCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobCreateExceptionHeaders = { + serializedName: "PageBlob_createExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobCreateExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUploadPagesHeaders = { + serializedName: "PageBlob_uploadPagesHeaders", + type: { + name: "Composite", + className: "PageBlobUploadPagesHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUploadPagesExceptionHeaders = { + serializedName: "PageBlob_uploadPagesExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobUploadPagesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobClearPagesHeaders = { + serializedName: "PageBlob_clearPagesHeaders", + type: { + name: "Composite", + className: "PageBlobClearPagesHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobClearPagesExceptionHeaders = { + serializedName: "PageBlob_clearPagesExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobClearPagesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUploadPagesFromURLHeaders = { + serializedName: "PageBlob_uploadPagesFromURLHeaders", + type: { + name: "Composite", + className: "PageBlobUploadPagesFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUploadPagesFromURLExceptionHeaders = { + serializedName: "PageBlob_uploadPagesFromURLExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobUploadPagesFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobGetPageRangesHeaders = { + serializedName: "PageBlob_getPageRangesHeaders", + type: { + name: "Composite", + className: "PageBlobGetPageRangesHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + xmlName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobGetPageRangesExceptionHeaders = { + serializedName: "PageBlob_getPageRangesExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobGetPageRangesExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobGetPageRangesDiffHeaders = { + serializedName: "PageBlob_getPageRangesDiffHeaders", + type: { + name: "Composite", + className: "PageBlobGetPageRangesDiffHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + xmlName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobGetPageRangesDiffExceptionHeaders = { + serializedName: "PageBlob_getPageRangesDiffExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobGetPageRangesDiffExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobResizeHeaders = { + serializedName: "PageBlob_resizeHeaders", + type: { + name: "Composite", + className: "PageBlobResizeHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobResizeExceptionHeaders = { + serializedName: "PageBlob_resizeExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobResizeExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUpdateSequenceNumberHeaders = { + serializedName: "PageBlob_updateSequenceNumberHeaders", + type: { + name: "Composite", + className: "PageBlobUpdateSequenceNumberHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobUpdateSequenceNumberExceptionHeaders = { + serializedName: "PageBlob_updateSequenceNumberExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobUpdateSequenceNumberExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobCopyIncrementalHeaders = { + serializedName: "PageBlob_copyIncrementalHeaders", + type: { + name: "Composite", + className: "PageBlobCopyIncrementalHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + xmlName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + xmlName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: ["pending", "success", "aborted", "failed"] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var PageBlobCopyIncrementalExceptionHeaders = { + serializedName: "PageBlob_copyIncrementalExceptionHeaders", + type: { + name: "Composite", + className: "PageBlobCopyIncrementalExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobCreateHeaders = { + serializedName: "AppendBlob_createHeaders", + type: { + name: "Composite", + className: "AppendBlobCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobCreateExceptionHeaders = { + serializedName: "AppendBlob_createExceptionHeaders", + type: { + name: "Composite", + className: "AppendBlobCreateExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobAppendBlockHeaders = { + serializedName: "AppendBlob_appendBlockHeaders", + type: { + name: "Composite", + className: "AppendBlobAppendBlockHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobAppendOffset: { + serializedName: "x-ms-blob-append-offset", + xmlName: "x-ms-blob-append-offset", + type: { + name: "String" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + xmlName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobAppendBlockExceptionHeaders = { + serializedName: "AppendBlob_appendBlockExceptionHeaders", + type: { + name: "Composite", + className: "AppendBlobAppendBlockExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobAppendBlockFromUrlHeaders = { + serializedName: "AppendBlob_appendBlockFromUrlHeaders", + type: { + name: "Composite", + className: "AppendBlobAppendBlockFromUrlHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobAppendOffset: { + serializedName: "x-ms-blob-append-offset", + xmlName: "x-ms-blob-append-offset", + type: { + name: "String" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + xmlName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobAppendBlockFromUrlExceptionHeaders = { + serializedName: "AppendBlob_appendBlockFromUrlExceptionHeaders", + type: { + name: "Composite", + className: "AppendBlobAppendBlockFromUrlExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var AppendBlobSealHeaders = { + serializedName: "AppendBlob_sealHeaders", + type: { + name: "Composite", + className: "AppendBlobSealHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isSealed: { + serializedName: "x-ms-blob-sealed", + xmlName: "x-ms-blob-sealed", + type: { + name: "Boolean" + } + } + } + } + }; + var AppendBlobSealExceptionHeaders = { + serializedName: "AppendBlob_sealExceptionHeaders", + type: { + name: "Composite", + className: "AppendBlobSealExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobUploadHeaders = { + serializedName: "BlockBlob_uploadHeaders", + type: { + name: "Composite", + className: "BlockBlobUploadHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobUploadExceptionHeaders = { + serializedName: "BlockBlob_uploadExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobUploadExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobPutBlobFromUrlHeaders = { + serializedName: "BlockBlob_putBlobFromUrlHeaders", + type: { + name: "Composite", + className: "BlockBlobPutBlobFromUrlHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobPutBlobFromUrlExceptionHeaders = { + serializedName: "BlockBlob_putBlobFromUrlExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobPutBlobFromUrlExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobStageBlockHeaders = { + serializedName: "BlockBlob_stageBlockHeaders", + type: { + name: "Composite", + className: "BlockBlobStageBlockHeaders", + modelProperties: { + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobStageBlockExceptionHeaders = { + serializedName: "BlockBlob_stageBlockExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobStageBlockExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobStageBlockFromURLHeaders = { + serializedName: "BlockBlob_stageBlockFromURLHeaders", + type: { + name: "Composite", + className: "BlockBlobStageBlockFromURLHeaders", + modelProperties: { + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobStageBlockFromURLExceptionHeaders = { + serializedName: "BlockBlob_stageBlockFromURLExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobStageBlockFromURLExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobCommitBlockListHeaders = { + serializedName: "BlockBlob_commitBlockListHeaders", + type: { + name: "Composite", + className: "BlockBlobCommitBlockListHeaders", + modelProperties: { + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + xmlName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + xmlName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + xmlName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobCommitBlockListExceptionHeaders = { + serializedName: "BlockBlob_commitBlockListExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobCommitBlockListExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobGetBlockListHeaders = { + serializedName: "BlockBlob_getBlockListHeaders", + type: { + name: "Composite", + className: "BlockBlobGetBlockListHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + xmlName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + xmlName: "etag", + type: { + name: "String" + } + }, + contentType: { + serializedName: "content-type", + xmlName: "content-type", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + xmlName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var BlockBlobGetBlockListExceptionHeaders = { + serializedName: "BlockBlob_getBlockListExceptionHeaders", + type: { + name: "Composite", + className: "BlockBlobGetBlockListExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } + }; + var Mappers = /* @__PURE__ */ Object.freeze({ + __proto__: null, + AccessPolicy, + AppendBlobAppendBlockExceptionHeaders, + AppendBlobAppendBlockFromUrlExceptionHeaders, + AppendBlobAppendBlockFromUrlHeaders, + AppendBlobAppendBlockHeaders, + AppendBlobCreateExceptionHeaders, + AppendBlobCreateHeaders, + AppendBlobSealExceptionHeaders, + AppendBlobSealHeaders, + ArrowConfiguration, + ArrowField, + BlobAbortCopyFromURLExceptionHeaders, + BlobAbortCopyFromURLHeaders, + BlobAcquireLeaseExceptionHeaders, + BlobAcquireLeaseHeaders, + BlobBreakLeaseExceptionHeaders, + BlobBreakLeaseHeaders, + BlobChangeLeaseExceptionHeaders, + BlobChangeLeaseHeaders, + BlobCopyFromURLExceptionHeaders, + BlobCopyFromURLHeaders, + BlobCreateSnapshotExceptionHeaders, + BlobCreateSnapshotHeaders, + BlobDeleteExceptionHeaders, + BlobDeleteHeaders, + BlobDeleteImmutabilityPolicyExceptionHeaders, + BlobDeleteImmutabilityPolicyHeaders, + BlobDownloadExceptionHeaders, + BlobDownloadHeaders, + BlobFlatListSegment, + BlobGetAccountInfoExceptionHeaders, + BlobGetAccountInfoHeaders, + BlobGetPropertiesExceptionHeaders, + BlobGetPropertiesHeaders, + BlobGetTagsExceptionHeaders, + BlobGetTagsHeaders, + BlobHierarchyListSegment, + BlobItemInternal, + BlobName, + BlobPrefix, + BlobPropertiesInternal, + BlobQueryExceptionHeaders, + BlobQueryHeaders, + BlobReleaseLeaseExceptionHeaders, + BlobReleaseLeaseHeaders, + BlobRenewLeaseExceptionHeaders, + BlobRenewLeaseHeaders, + BlobServiceProperties, + BlobServiceStatistics, + BlobSetExpiryExceptionHeaders, + BlobSetExpiryHeaders, + BlobSetHttpHeadersExceptionHeaders, + BlobSetHttpHeadersHeaders, + BlobSetImmutabilityPolicyExceptionHeaders, + BlobSetImmutabilityPolicyHeaders, + BlobSetLegalHoldExceptionHeaders, + BlobSetLegalHoldHeaders, + BlobSetMetadataExceptionHeaders, + BlobSetMetadataHeaders, + BlobSetTagsExceptionHeaders, + BlobSetTagsHeaders, + BlobSetTierExceptionHeaders, + BlobSetTierHeaders, + BlobStartCopyFromURLExceptionHeaders, + BlobStartCopyFromURLHeaders, + BlobTag, + BlobTags, + BlobUndeleteExceptionHeaders, + BlobUndeleteHeaders, + Block, + BlockBlobCommitBlockListExceptionHeaders, + BlockBlobCommitBlockListHeaders, + BlockBlobGetBlockListExceptionHeaders, + BlockBlobGetBlockListHeaders, + BlockBlobPutBlobFromUrlExceptionHeaders, + BlockBlobPutBlobFromUrlHeaders, + BlockBlobStageBlockExceptionHeaders, + BlockBlobStageBlockFromURLExceptionHeaders, + BlockBlobStageBlockFromURLHeaders, + BlockBlobStageBlockHeaders, + BlockBlobUploadExceptionHeaders, + BlockBlobUploadHeaders, + BlockList, + BlockLookupList, + ClearRange, + ContainerAcquireLeaseExceptionHeaders, + ContainerAcquireLeaseHeaders, + ContainerBreakLeaseExceptionHeaders, + ContainerBreakLeaseHeaders, + ContainerChangeLeaseExceptionHeaders, + ContainerChangeLeaseHeaders, + ContainerCreateExceptionHeaders, + ContainerCreateHeaders, + ContainerDeleteExceptionHeaders, + ContainerDeleteHeaders, + ContainerFilterBlobsExceptionHeaders, + ContainerFilterBlobsHeaders, + ContainerGetAccessPolicyExceptionHeaders, + ContainerGetAccessPolicyHeaders, + ContainerGetAccountInfoExceptionHeaders, + ContainerGetAccountInfoHeaders, + ContainerGetPropertiesExceptionHeaders, + ContainerGetPropertiesHeaders, + ContainerItem, + ContainerListBlobFlatSegmentExceptionHeaders, + ContainerListBlobFlatSegmentHeaders, + ContainerListBlobHierarchySegmentExceptionHeaders, + ContainerListBlobHierarchySegmentHeaders, + ContainerProperties, + ContainerReleaseLeaseExceptionHeaders, + ContainerReleaseLeaseHeaders, + ContainerRenameExceptionHeaders, + ContainerRenameHeaders, + ContainerRenewLeaseExceptionHeaders, + ContainerRenewLeaseHeaders, + ContainerRestoreExceptionHeaders, + ContainerRestoreHeaders, + ContainerSetAccessPolicyExceptionHeaders, + ContainerSetAccessPolicyHeaders, + ContainerSetMetadataExceptionHeaders, + ContainerSetMetadataHeaders, + ContainerSubmitBatchExceptionHeaders, + ContainerSubmitBatchHeaders, + CorsRule, + DelimitedTextConfiguration, + FilterBlobItem, + FilterBlobSegment, + GeoReplication, + JsonTextConfiguration, + KeyInfo, + ListBlobsFlatSegmentResponse, + ListBlobsHierarchySegmentResponse, + ListContainersSegmentResponse, + Logging, + Metrics, + PageBlobClearPagesExceptionHeaders, + PageBlobClearPagesHeaders, + PageBlobCopyIncrementalExceptionHeaders, + PageBlobCopyIncrementalHeaders, + PageBlobCreateExceptionHeaders, + PageBlobCreateHeaders, + PageBlobGetPageRangesDiffExceptionHeaders, + PageBlobGetPageRangesDiffHeaders, + PageBlobGetPageRangesExceptionHeaders, + PageBlobGetPageRangesHeaders, + PageBlobResizeExceptionHeaders, + PageBlobResizeHeaders, + PageBlobUpdateSequenceNumberExceptionHeaders, + PageBlobUpdateSequenceNumberHeaders, + PageBlobUploadPagesExceptionHeaders, + PageBlobUploadPagesFromURLExceptionHeaders, + PageBlobUploadPagesFromURLHeaders, + PageBlobUploadPagesHeaders, + PageList, + PageRange, + QueryFormat, + QueryRequest, + QuerySerialization, + RetentionPolicy, + ServiceFilterBlobsExceptionHeaders, + ServiceFilterBlobsHeaders, + ServiceGetAccountInfoExceptionHeaders, + ServiceGetAccountInfoHeaders, + ServiceGetPropertiesExceptionHeaders, + ServiceGetPropertiesHeaders, + ServiceGetStatisticsExceptionHeaders, + ServiceGetStatisticsHeaders, + ServiceGetUserDelegationKeyExceptionHeaders, + ServiceGetUserDelegationKeyHeaders, + ServiceListContainersSegmentExceptionHeaders, + ServiceListContainersSegmentHeaders, + ServiceSetPropertiesExceptionHeaders, + ServiceSetPropertiesHeaders, + ServiceSubmitBatchExceptionHeaders, + ServiceSubmitBatchHeaders, + SignedIdentifier, + StaticWebsite, + StorageError, + UserDelegationKey + }); + var contentType = { + parameterPath: ["options", "contentType"], + mapper: { + defaultValue: "application/xml", + isConstant: true, + serializedName: "Content-Type", + type: { + name: "String" + } + } + }; + var blobServiceProperties = { + parameterPath: "blobServiceProperties", + mapper: BlobServiceProperties + }; + var accept = { + parameterPath: "accept", + mapper: { + defaultValue: "application/xml", + isConstant: true, + serializedName: "Accept", + type: { + name: "String" + } + } + }; + var url = { + parameterPath: "url", + mapper: { + serializedName: "url", + required: true, + xmlName: "url", + type: { + name: "String" + } + }, + skipEncoding: true + }; + var restype = { + parameterPath: "restype", + mapper: { + defaultValue: "service", + isConstant: true, + serializedName: "restype", + type: { + name: "String" + } + } + }; + var comp = { + parameterPath: "comp", + mapper: { + defaultValue: "properties", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var timeoutInSeconds = { + parameterPath: ["options", "timeoutInSeconds"], + mapper: { + constraints: { + InclusiveMinimum: 0 + }, + serializedName: "timeout", + xmlName: "timeout", + type: { + name: "Number" + } + } + }; + var version = { + parameterPath: "version", + mapper: { + defaultValue: "2024-11-04", + isConstant: true, + serializedName: "x-ms-version", + type: { + name: "String" + } + } + }; + var requestId = { + parameterPath: ["options", "requestId"], + mapper: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + } + }; + var accept1 = { + parameterPath: "accept", + mapper: { + defaultValue: "application/xml", + isConstant: true, + serializedName: "Accept", + type: { + name: "String" + } + } + }; + var comp1 = { + parameterPath: "comp", + mapper: { + defaultValue: "stats", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var comp2 = { + parameterPath: "comp", + mapper: { + defaultValue: "list", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var prefix = { + parameterPath: ["options", "prefix"], + mapper: { + serializedName: "prefix", + xmlName: "prefix", + type: { + name: "String" + } + } + }; + var marker = { + parameterPath: ["options", "marker"], + mapper: { + serializedName: "marker", + xmlName: "marker", + type: { + name: "String" + } + } + }; + var maxPageSize = { + parameterPath: ["options", "maxPageSize"], + mapper: { + constraints: { + InclusiveMinimum: 1 + }, + serializedName: "maxresults", + xmlName: "maxresults", + type: { + name: "Number" + } + } + }; + var include = { + parameterPath: ["options", "include"], + mapper: { + serializedName: "include", + xmlName: "include", + xmlElementName: "ListContainersIncludeType", + type: { + name: "Sequence", + element: { + type: { + name: "Enum", + allowedValues: ["metadata", "deleted", "system"] + } + } + } + }, + collectionFormat: "CSV" + }; + var keyInfo = { + parameterPath: "keyInfo", + mapper: KeyInfo + }; + var comp3 = { + parameterPath: "comp", + mapper: { + defaultValue: "userdelegationkey", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var restype1 = { + parameterPath: "restype", + mapper: { + defaultValue: "account", + isConstant: true, + serializedName: "restype", + type: { + name: "String" + } + } + }; + var body = { + parameterPath: "body", + mapper: { + serializedName: "body", + required: true, + xmlName: "body", + type: { + name: "Stream" + } + } + }; + var comp4 = { + parameterPath: "comp", + mapper: { + defaultValue: "batch", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var contentLength = { + parameterPath: "contentLength", + mapper: { + serializedName: "Content-Length", + required: true, + xmlName: "Content-Length", + type: { + name: "Number" + } + } + }; + var multipartContentType = { + parameterPath: "multipartContentType", + mapper: { + serializedName: "Content-Type", + required: true, + xmlName: "Content-Type", + type: { + name: "String" + } + } + }; + var comp5 = { + parameterPath: "comp", + mapper: { + defaultValue: "blobs", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var where = { + parameterPath: ["options", "where"], + mapper: { + serializedName: "where", + xmlName: "where", + type: { + name: "String" + } + } + }; + var restype2 = { + parameterPath: "restype", + mapper: { + defaultValue: "container", + isConstant: true, + serializedName: "restype", + type: { + name: "String" + } + } + }; + var metadata = { + parameterPath: ["options", "metadata"], + mapper: { + serializedName: "x-ms-meta", + xmlName: "x-ms-meta", + headerCollectionPrefix: "x-ms-meta-", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + } + }; + var access2 = { + parameterPath: ["options", "access"], + mapper: { + serializedName: "x-ms-blob-public-access", + xmlName: "x-ms-blob-public-access", + type: { + name: "Enum", + allowedValues: ["container", "blob"] + } + } + }; + var defaultEncryptionScope = { + parameterPath: [ + "options", + "containerEncryptionScope", + "defaultEncryptionScope" + ], + mapper: { + serializedName: "x-ms-default-encryption-scope", + xmlName: "x-ms-default-encryption-scope", + type: { + name: "String" + } + } + }; + var preventEncryptionScopeOverride = { + parameterPath: [ + "options", + "containerEncryptionScope", + "preventEncryptionScopeOverride" + ], + mapper: { + serializedName: "x-ms-deny-encryption-scope-override", + xmlName: "x-ms-deny-encryption-scope-override", + type: { + name: "Boolean" + } + } + }; + var leaseId = { + parameterPath: ["options", "leaseAccessConditions", "leaseId"], + mapper: { + serializedName: "x-ms-lease-id", + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + } + }; + var ifModifiedSince = { + parameterPath: ["options", "modifiedAccessConditions", "ifModifiedSince"], + mapper: { + serializedName: "If-Modified-Since", + xmlName: "If-Modified-Since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var ifUnmodifiedSince = { + parameterPath: ["options", "modifiedAccessConditions", "ifUnmodifiedSince"], + mapper: { + serializedName: "If-Unmodified-Since", + xmlName: "If-Unmodified-Since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var comp6 = { + parameterPath: "comp", + mapper: { + defaultValue: "metadata", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var comp7 = { + parameterPath: "comp", + mapper: { + defaultValue: "acl", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var containerAcl = { + parameterPath: ["options", "containerAcl"], + mapper: { + serializedName: "containerAcl", + xmlName: "SignedIdentifiers", + xmlIsWrapped: true, + xmlElementName: "SignedIdentifier", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "SignedIdentifier" + } + } + } + } + }; + var comp8 = { + parameterPath: "comp", + mapper: { + defaultValue: "undelete", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var deletedContainerName = { + parameterPath: ["options", "deletedContainerName"], + mapper: { + serializedName: "x-ms-deleted-container-name", + xmlName: "x-ms-deleted-container-name", + type: { + name: "String" + } + } + }; + var deletedContainerVersion = { + parameterPath: ["options", "deletedContainerVersion"], + mapper: { + serializedName: "x-ms-deleted-container-version", + xmlName: "x-ms-deleted-container-version", + type: { + name: "String" + } + } + }; + var comp9 = { + parameterPath: "comp", + mapper: { + defaultValue: "rename", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var sourceContainerName = { + parameterPath: "sourceContainerName", + mapper: { + serializedName: "x-ms-source-container-name", + required: true, + xmlName: "x-ms-source-container-name", + type: { + name: "String" + } + } + }; + var sourceLeaseId = { + parameterPath: ["options", "sourceLeaseId"], + mapper: { + serializedName: "x-ms-source-lease-id", + xmlName: "x-ms-source-lease-id", + type: { + name: "String" + } + } + }; + var comp10 = { + parameterPath: "comp", + mapper: { + defaultValue: "lease", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var action = { + parameterPath: "action", + mapper: { + defaultValue: "acquire", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var duration = { + parameterPath: ["options", "duration"], + mapper: { + serializedName: "x-ms-lease-duration", + xmlName: "x-ms-lease-duration", + type: { + name: "Number" + } + } + }; + var proposedLeaseId = { + parameterPath: ["options", "proposedLeaseId"], + mapper: { + serializedName: "x-ms-proposed-lease-id", + xmlName: "x-ms-proposed-lease-id", + type: { + name: "String" + } + } + }; + var action1 = { + parameterPath: "action", + mapper: { + defaultValue: "release", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var leaseId1 = { + parameterPath: "leaseId", + mapper: { + serializedName: "x-ms-lease-id", + required: true, + xmlName: "x-ms-lease-id", + type: { + name: "String" + } + } + }; + var action2 = { + parameterPath: "action", + mapper: { + defaultValue: "renew", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var action3 = { + parameterPath: "action", + mapper: { + defaultValue: "break", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var breakPeriod = { + parameterPath: ["options", "breakPeriod"], + mapper: { + serializedName: "x-ms-lease-break-period", + xmlName: "x-ms-lease-break-period", + type: { + name: "Number" + } + } + }; + var action4 = { + parameterPath: "action", + mapper: { + defaultValue: "change", + isConstant: true, + serializedName: "x-ms-lease-action", + type: { + name: "String" + } + } + }; + var proposedLeaseId1 = { + parameterPath: "proposedLeaseId", + mapper: { + serializedName: "x-ms-proposed-lease-id", + required: true, + xmlName: "x-ms-proposed-lease-id", + type: { + name: "String" + } + } + }; + var include1 = { + parameterPath: ["options", "include"], + mapper: { + serializedName: "include", + xmlName: "include", + xmlElementName: "ListBlobsIncludeItem", + type: { + name: "Sequence", + element: { + type: { + name: "Enum", + allowedValues: [ + "copy", + "deleted", + "metadata", + "snapshots", + "uncommittedblobs", + "versions", + "tags", + "immutabilitypolicy", + "legalhold", + "deletedwithversions" + ] + } + } + } + }, + collectionFormat: "CSV" + }; + var delimiter = { + parameterPath: "delimiter", + mapper: { + serializedName: "delimiter", + required: true, + xmlName: "delimiter", + type: { + name: "String" + } + } + }; + var snapshot = { + parameterPath: ["options", "snapshot"], + mapper: { + serializedName: "snapshot", + xmlName: "snapshot", + type: { + name: "String" + } + } + }; + var versionId = { + parameterPath: ["options", "versionId"], + mapper: { + serializedName: "versionid", + xmlName: "versionid", + type: { + name: "String" + } + } + }; + var range = { + parameterPath: ["options", "range"], + mapper: { + serializedName: "x-ms-range", + xmlName: "x-ms-range", + type: { + name: "String" + } + } + }; + var rangeGetContentMD5 = { + parameterPath: ["options", "rangeGetContentMD5"], + mapper: { + serializedName: "x-ms-range-get-content-md5", + xmlName: "x-ms-range-get-content-md5", + type: { + name: "Boolean" + } + } + }; + var rangeGetContentCRC64 = { + parameterPath: ["options", "rangeGetContentCRC64"], + mapper: { + serializedName: "x-ms-range-get-content-crc64", + xmlName: "x-ms-range-get-content-crc64", + type: { + name: "Boolean" + } + } + }; + var encryptionKey = { + parameterPath: ["options", "cpkInfo", "encryptionKey"], + mapper: { + serializedName: "x-ms-encryption-key", + xmlName: "x-ms-encryption-key", + type: { + name: "String" + } + } + }; + var encryptionKeySha256 = { + parameterPath: ["options", "cpkInfo", "encryptionKeySha256"], + mapper: { + serializedName: "x-ms-encryption-key-sha256", + xmlName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + } + }; + var encryptionAlgorithm = { + parameterPath: ["options", "cpkInfo", "encryptionAlgorithm"], + mapper: { + serializedName: "x-ms-encryption-algorithm", + xmlName: "x-ms-encryption-algorithm", + type: { + name: "String" + } + } + }; + var ifMatch = { + parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], + mapper: { + serializedName: "If-Match", + xmlName: "If-Match", + type: { + name: "String" + } + } + }; + var ifNoneMatch = { + parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], + mapper: { + serializedName: "If-None-Match", + xmlName: "If-None-Match", + type: { + name: "String" + } + } + }; + var ifTags = { + parameterPath: ["options", "modifiedAccessConditions", "ifTags"], + mapper: { + serializedName: "x-ms-if-tags", + xmlName: "x-ms-if-tags", + type: { + name: "String" + } + } + }; + var deleteSnapshots = { + parameterPath: ["options", "deleteSnapshots"], + mapper: { + serializedName: "x-ms-delete-snapshots", + xmlName: "x-ms-delete-snapshots", + type: { + name: "Enum", + allowedValues: ["include", "only"] + } + } + }; + var blobDeleteType = { + parameterPath: ["options", "blobDeleteType"], + mapper: { + serializedName: "deletetype", + xmlName: "deletetype", + type: { + name: "String" + } + } + }; + var comp11 = { + parameterPath: "comp", + mapper: { + defaultValue: "expiry", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var expiryOptions = { + parameterPath: "expiryOptions", + mapper: { + serializedName: "x-ms-expiry-option", + required: true, + xmlName: "x-ms-expiry-option", + type: { + name: "String" + } + } + }; + var expiresOn = { + parameterPath: ["options", "expiresOn"], + mapper: { + serializedName: "x-ms-expiry-time", + xmlName: "x-ms-expiry-time", + type: { + name: "String" + } + } + }; + var blobCacheControl = { + parameterPath: ["options", "blobHttpHeaders", "blobCacheControl"], + mapper: { + serializedName: "x-ms-blob-cache-control", + xmlName: "x-ms-blob-cache-control", + type: { + name: "String" + } + } + }; + var blobContentType = { + parameterPath: ["options", "blobHttpHeaders", "blobContentType"], + mapper: { + serializedName: "x-ms-blob-content-type", + xmlName: "x-ms-blob-content-type", + type: { + name: "String" + } + } + }; + var blobContentMD5 = { + parameterPath: ["options", "blobHttpHeaders", "blobContentMD5"], + mapper: { + serializedName: "x-ms-blob-content-md5", + xmlName: "x-ms-blob-content-md5", + type: { + name: "ByteArray" + } + } + }; + var blobContentEncoding = { + parameterPath: ["options", "blobHttpHeaders", "blobContentEncoding"], + mapper: { + serializedName: "x-ms-blob-content-encoding", + xmlName: "x-ms-blob-content-encoding", + type: { + name: "String" + } + } + }; + var blobContentLanguage = { + parameterPath: ["options", "blobHttpHeaders", "blobContentLanguage"], + mapper: { + serializedName: "x-ms-blob-content-language", + xmlName: "x-ms-blob-content-language", + type: { + name: "String" + } + } + }; + var blobContentDisposition = { + parameterPath: ["options", "blobHttpHeaders", "blobContentDisposition"], + mapper: { + serializedName: "x-ms-blob-content-disposition", + xmlName: "x-ms-blob-content-disposition", + type: { + name: "String" + } + } + }; + var comp12 = { + parameterPath: "comp", + mapper: { + defaultValue: "immutabilityPolicies", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var immutabilityPolicyExpiry = { + parameterPath: ["options", "immutabilityPolicyExpiry"], + mapper: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + } + }; + var immutabilityPolicyMode = { + parameterPath: ["options", "immutabilityPolicyMode"], + mapper: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + } + }; + var comp13 = { + parameterPath: "comp", + mapper: { + defaultValue: "legalhold", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var legalHold = { + parameterPath: "legalHold", + mapper: { + serializedName: "x-ms-legal-hold", + required: true, + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } + }; + var encryptionScope = { + parameterPath: ["options", "encryptionScope"], + mapper: { + serializedName: "x-ms-encryption-scope", + xmlName: "x-ms-encryption-scope", + type: { + name: "String" + } + } + }; + var comp14 = { + parameterPath: "comp", + mapper: { + defaultValue: "snapshot", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var tier = { + parameterPath: ["options", "tier"], + mapper: { + serializedName: "x-ms-access-tier", + xmlName: "x-ms-access-tier", + type: { + name: "Enum", + allowedValues: [ + "P4", + "P6", + "P10", + "P15", + "P20", + "P30", + "P40", + "P50", + "P60", + "P70", + "P80", + "Hot", + "Cool", + "Archive", + "Cold" + ] + } + } + }; + var rehydratePriority = { + parameterPath: ["options", "rehydratePriority"], + mapper: { + serializedName: "x-ms-rehydrate-priority", + xmlName: "x-ms-rehydrate-priority", + type: { + name: "Enum", + allowedValues: ["High", "Standard"] + } + } + }; + var sourceIfModifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfModifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-modified-since", + xmlName: "x-ms-source-if-modified-since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var sourceIfUnmodifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfUnmodifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-unmodified-since", + xmlName: "x-ms-source-if-unmodified-since", + type: { + name: "DateTimeRfc1123" + } + } + }; + var sourceIfMatch = { + parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], + mapper: { + serializedName: "x-ms-source-if-match", + xmlName: "x-ms-source-if-match", + type: { + name: "String" + } + } + }; + var sourceIfNoneMatch = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfNoneMatch" + ], + mapper: { + serializedName: "x-ms-source-if-none-match", + xmlName: "x-ms-source-if-none-match", + type: { + name: "String" + } + } + }; + var sourceIfTags = { + parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfTags"], + mapper: { + serializedName: "x-ms-source-if-tags", + xmlName: "x-ms-source-if-tags", + type: { + name: "String" + } + } + }; + var copySource = { + parameterPath: "copySource", + mapper: { + serializedName: "x-ms-copy-source", + required: true, + xmlName: "x-ms-copy-source", + type: { + name: "String" + } + } + }; + var blobTagsString = { + parameterPath: ["options", "blobTagsString"], + mapper: { + serializedName: "x-ms-tags", + xmlName: "x-ms-tags", + type: { + name: "String" + } + } + }; + var sealBlob = { + parameterPath: ["options", "sealBlob"], + mapper: { + serializedName: "x-ms-seal-blob", + xmlName: "x-ms-seal-blob", + type: { + name: "Boolean" + } + } + }; + var legalHold1 = { + parameterPath: ["options", "legalHold"], + mapper: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } + }; + var xMsRequiresSync = { + parameterPath: "xMsRequiresSync", + mapper: { + defaultValue: "true", + isConstant: true, + serializedName: "x-ms-requires-sync", + type: { + name: "String" + } + } + }; + var sourceContentMD5 = { + parameterPath: ["options", "sourceContentMD5"], + mapper: { + serializedName: "x-ms-source-content-md5", + xmlName: "x-ms-source-content-md5", + type: { + name: "ByteArray" + } + } + }; + var copySourceAuthorization = { + parameterPath: ["options", "copySourceAuthorization"], + mapper: { + serializedName: "x-ms-copy-source-authorization", + xmlName: "x-ms-copy-source-authorization", + type: { + name: "String" + } + } + }; + var copySourceTags = { + parameterPath: ["options", "copySourceTags"], + mapper: { + serializedName: "x-ms-copy-source-tag-option", + xmlName: "x-ms-copy-source-tag-option", + type: { + name: "Enum", + allowedValues: ["REPLACE", "COPY"] + } + } + }; + var comp15 = { + parameterPath: "comp", + mapper: { + defaultValue: "copy", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var copyActionAbortConstant = { + parameterPath: "copyActionAbortConstant", + mapper: { + defaultValue: "abort", + isConstant: true, + serializedName: "x-ms-copy-action", + type: { + name: "String" + } + } + }; + var copyId = { + parameterPath: "copyId", + mapper: { + serializedName: "copyid", + required: true, + xmlName: "copyid", + type: { + name: "String" + } + } + }; + var comp16 = { + parameterPath: "comp", + mapper: { + defaultValue: "tier", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var tier1 = { + parameterPath: "tier", + mapper: { + serializedName: "x-ms-access-tier", + required: true, + xmlName: "x-ms-access-tier", + type: { + name: "Enum", + allowedValues: [ + "P4", + "P6", + "P10", + "P15", + "P20", + "P30", + "P40", + "P50", + "P60", + "P70", + "P80", + "Hot", + "Cool", + "Archive", + "Cold" + ] + } + } + }; + var queryRequest = { + parameterPath: ["options", "queryRequest"], + mapper: QueryRequest + }; + var comp17 = { + parameterPath: "comp", + mapper: { + defaultValue: "query", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var comp18 = { + parameterPath: "comp", + mapper: { + defaultValue: "tags", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var tags = { + parameterPath: ["options", "tags"], + mapper: BlobTags + }; + var transactionalContentMD5 = { + parameterPath: ["options", "transactionalContentMD5"], + mapper: { + serializedName: "Content-MD5", + xmlName: "Content-MD5", + type: { + name: "ByteArray" + } + } + }; + var transactionalContentCrc64 = { + parameterPath: ["options", "transactionalContentCrc64"], + mapper: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + } + }; + var blobType = { + parameterPath: "blobType", + mapper: { + defaultValue: "PageBlob", + isConstant: true, + serializedName: "x-ms-blob-type", + type: { + name: "String" + } + } + }; + var blobContentLength = { + parameterPath: "blobContentLength", + mapper: { + serializedName: "x-ms-blob-content-length", + required: true, + xmlName: "x-ms-blob-content-length", + type: { + name: "Number" + } + } + }; + var blobSequenceNumber = { + parameterPath: ["options", "blobSequenceNumber"], + mapper: { + defaultValue: 0, + serializedName: "x-ms-blob-sequence-number", + xmlName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + } + }; + var contentType1 = { + parameterPath: ["options", "contentType"], + mapper: { + defaultValue: "application/octet-stream", + isConstant: true, + serializedName: "Content-Type", + type: { + name: "String" + } + } + }; + var body1 = { + parameterPath: "body", + mapper: { + serializedName: "body", + required: true, + xmlName: "body", + type: { + name: "Stream" + } + } + }; + var accept2 = { + parameterPath: "accept", + mapper: { + defaultValue: "application/xml", + isConstant: true, + serializedName: "Accept", + type: { + name: "String" + } + } + }; + var comp19 = { + parameterPath: "comp", + mapper: { + defaultValue: "page", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var pageWrite = { + parameterPath: "pageWrite", + mapper: { + defaultValue: "update", + isConstant: true, + serializedName: "x-ms-page-write", + type: { + name: "String" + } + } + }; + var ifSequenceNumberLessThanOrEqualTo = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberLessThanOrEqualTo" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-le", + xmlName: "x-ms-if-sequence-number-le", + type: { + name: "Number" + } + } + }; + var ifSequenceNumberLessThan = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberLessThan" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-lt", + xmlName: "x-ms-if-sequence-number-lt", + type: { + name: "Number" + } + } + }; + var ifSequenceNumberEqualTo = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberEqualTo" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-eq", + xmlName: "x-ms-if-sequence-number-eq", + type: { + name: "Number" + } + } + }; + var pageWrite1 = { + parameterPath: "pageWrite", + mapper: { + defaultValue: "clear", + isConstant: true, + serializedName: "x-ms-page-write", + type: { + name: "String" + } + } + }; + var sourceUrl = { + parameterPath: "sourceUrl", + mapper: { + serializedName: "x-ms-copy-source", + required: true, + xmlName: "x-ms-copy-source", + type: { + name: "String" + } + } + }; + var sourceRange = { + parameterPath: "sourceRange", + mapper: { + serializedName: "x-ms-source-range", + required: true, + xmlName: "x-ms-source-range", + type: { + name: "String" + } + } + }; + var sourceContentCrc64 = { + parameterPath: ["options", "sourceContentCrc64"], + mapper: { + serializedName: "x-ms-source-content-crc64", + xmlName: "x-ms-source-content-crc64", + type: { + name: "ByteArray" + } + } + }; + var range1 = { + parameterPath: "range", + mapper: { + serializedName: "x-ms-range", + required: true, + xmlName: "x-ms-range", + type: { + name: "String" + } + } + }; + var comp20 = { + parameterPath: "comp", + mapper: { + defaultValue: "pagelist", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var prevsnapshot = { + parameterPath: ["options", "prevsnapshot"], + mapper: { + serializedName: "prevsnapshot", + xmlName: "prevsnapshot", + type: { + name: "String" + } + } + }; + var prevSnapshotUrl = { + parameterPath: ["options", "prevSnapshotUrl"], + mapper: { + serializedName: "x-ms-previous-snapshot-url", + xmlName: "x-ms-previous-snapshot-url", + type: { + name: "String" + } + } + }; + var sequenceNumberAction = { + parameterPath: "sequenceNumberAction", + mapper: { + serializedName: "x-ms-sequence-number-action", + required: true, + xmlName: "x-ms-sequence-number-action", + type: { + name: "Enum", + allowedValues: ["max", "update", "increment"] + } + } + }; + var comp21 = { + parameterPath: "comp", + mapper: { + defaultValue: "incrementalcopy", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var blobType1 = { + parameterPath: "blobType", + mapper: { + defaultValue: "AppendBlob", + isConstant: true, + serializedName: "x-ms-blob-type", + type: { + name: "String" + } + } + }; + var comp22 = { + parameterPath: "comp", + mapper: { + defaultValue: "appendblock", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var maxSize = { + parameterPath: ["options", "appendPositionAccessConditions", "maxSize"], + mapper: { + serializedName: "x-ms-blob-condition-maxsize", + xmlName: "x-ms-blob-condition-maxsize", + type: { + name: "Number" + } + } + }; + var appendPosition = { + parameterPath: [ + "options", + "appendPositionAccessConditions", + "appendPosition" + ], + mapper: { + serializedName: "x-ms-blob-condition-appendpos", + xmlName: "x-ms-blob-condition-appendpos", + type: { + name: "Number" + } + } + }; + var sourceRange1 = { + parameterPath: ["options", "sourceRange"], + mapper: { + serializedName: "x-ms-source-range", + xmlName: "x-ms-source-range", + type: { + name: "String" + } + } + }; + var comp23 = { + parameterPath: "comp", + mapper: { + defaultValue: "seal", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var blobType2 = { + parameterPath: "blobType", + mapper: { + defaultValue: "BlockBlob", + isConstant: true, + serializedName: "x-ms-blob-type", + type: { + name: "String" + } + } + }; + var copySourceBlobProperties = { + parameterPath: ["options", "copySourceBlobProperties"], + mapper: { + serializedName: "x-ms-copy-source-blob-properties", + xmlName: "x-ms-copy-source-blob-properties", + type: { + name: "Boolean" + } + } + }; + var comp24 = { + parameterPath: "comp", + mapper: { + defaultValue: "block", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var blockId = { + parameterPath: "blockId", + mapper: { + serializedName: "blockid", + required: true, + xmlName: "blockid", + type: { + name: "String" + } + } + }; + var blocks = { + parameterPath: "blocks", + mapper: BlockLookupList + }; + var comp25 = { + parameterPath: "comp", + mapper: { + defaultValue: "blocklist", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } + }; + var listType = { + parameterPath: "listType", + mapper: { + defaultValue: "committed", + serializedName: "blocklisttype", + required: true, + xmlName: "blocklisttype", + type: { + name: "Enum", + allowedValues: ["committed", "uncommitted", "all"] + } + } + }; + var ServiceImpl = class { + /** + * Initialize a new instance of the class Service class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * Sets properties for a storage account's Blob service endpoint, including properties for Storage + * Analytics and CORS (Cross-Origin Resource Sharing) rules + * @param blobServiceProperties The StorageService properties. + * @param options The options parameters. + */ + setProperties(blobServiceProperties2, options) { + return this.client.sendOperationRequest({ blobServiceProperties: blobServiceProperties2, options }, setPropertiesOperationSpec); + } + /** + * gets the properties of a storage account's Blob service, including properties for Storage Analytics + * and CORS (Cross-Origin Resource Sharing) rules. + * @param options The options parameters. + */ + getProperties(options) { + return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec$2); + } + /** + * Retrieves statistics related to replication for the Blob service. It is only available on the + * secondary location endpoint when read-access geo-redundant replication is enabled for the storage + * account. + * @param options The options parameters. + */ + getStatistics(options) { + return this.client.sendOperationRequest({ options }, getStatisticsOperationSpec); + } + /** + * The List Containers Segment operation returns a list of the containers under the specified account + * @param options The options parameters. + */ + listContainersSegment(options) { + return this.client.sendOperationRequest({ options }, listContainersSegmentOperationSpec); + } + /** + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. + * @param keyInfo Key information + * @param options The options parameters. + */ + getUserDelegationKey(keyInfo2, options) { + return this.client.sendOperationRequest({ keyInfo: keyInfo2, options }, getUserDelegationKeyOperationSpec); + } + /** + * Returns the sku name and account kind + * @param options The options parameters. + */ + getAccountInfo(options) { + return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec$2); + } + /** + * The Batch operation allows multiple API calls to be embedded into a single HTTP request. + * @param contentLength The length of the request. + * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch + * boundary. Example header value: multipart/mixed; boundary=batch_ + * @param body Initial data + * @param options The options parameters. + */ + submitBatch(contentLength2, multipartContentType2, body2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, multipartContentType: multipartContentType2, body: body2, options }, submitBatchOperationSpec$1); + } + /** + * The Filter Blobs operation enables callers to list blobs across all containers whose tags match a + * given search expression. Filter blobs searches across all containers within a storage account but + * can be scoped within the expression to a single container. + * @param options The options parameters. + */ + filterBlobs(options) { + return this.client.sendOperationRequest({ options }, filterBlobsOperationSpec$1); + } + }; + var xmlSerializer$5 = coreClient__namespace.createSerializer( + Mappers, + /* isXml */ + true + ); + var setPropertiesOperationSpec = { + path: "/", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: ServiceSetPropertiesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceSetPropertiesExceptionHeaders + } + }, + requestBody: blobServiceProperties, + queryParameters: [ + restype, + comp, + timeoutInSeconds + ], + urlParameters: [url], + headerParameters: [ + contentType, + accept, + version, + requestId + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer$5 + }; + var getPropertiesOperationSpec$2 = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: BlobServiceProperties, + headersMapper: ServiceGetPropertiesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceGetPropertiesExceptionHeaders + } + }, + queryParameters: [ + restype, + comp, + timeoutInSeconds + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$5 + }; + var getStatisticsOperationSpec = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: BlobServiceStatistics, + headersMapper: ServiceGetStatisticsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceGetStatisticsExceptionHeaders + } + }, + queryParameters: [ + restype, + timeoutInSeconds, + comp1 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$5 + }; + var listContainersSegmentOperationSpec = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: ListContainersSegmentResponse, + headersMapper: ServiceListContainersSegmentHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceListContainersSegmentExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + comp2, + prefix, + marker, + maxPageSize, + include + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$5 + }; + var getUserDelegationKeyOperationSpec = { + path: "/", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: UserDelegationKey, + headersMapper: ServiceGetUserDelegationKeyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceGetUserDelegationKeyExceptionHeaders + } + }, + requestBody: keyInfo, + queryParameters: [ + restype, + timeoutInSeconds, + comp3 + ], + urlParameters: [url], + headerParameters: [ + contentType, + accept, + version, + requestId + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer$5 + }; + var getAccountInfoOperationSpec$2 = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + headersMapper: ServiceGetAccountInfoHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceGetAccountInfoExceptionHeaders + } + }, + queryParameters: [ + comp, + timeoutInSeconds, + restype1 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$5 + }; + var submitBatchOperationSpec$1 = { + path: "/", + httpMethod: "POST", + responses: { + 202: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: ServiceSubmitBatchHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceSubmitBatchExceptionHeaders + } + }, + requestBody: body, + queryParameters: [timeoutInSeconds, comp4], + urlParameters: [url], + headerParameters: [ + accept, + version, + requestId, + contentLength, + multipartContentType + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer$5 + }; + var filterBlobsOperationSpec$1 = { + path: "/", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: FilterBlobSegment, + headersMapper: ServiceFilterBlobsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceFilterBlobsExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + marker, + maxPageSize, + comp5, + where + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$5 + }; + var ContainerImpl = class { + /** + * Initialize a new instance of the class Container class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * creates a new container under the specified account. If the container with the same name already + * exists, the operation fails + * @param options The options parameters. + */ + create(options) { + return this.client.sendOperationRequest({ options }, createOperationSpec$2); + } + /** + * returns all user-defined metadata and system properties for the specified container. The data + * returned does not include the container's list of blobs + * @param options The options parameters. + */ + getProperties(options) { + return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec$1); + } + /** + * operation marks the specified container for deletion. The container and any blobs contained within + * it are later deleted during garbage collection + * @param options The options parameters. + */ + delete(options) { + return this.client.sendOperationRequest({ options }, deleteOperationSpec$1); + } + /** + * operation sets one or more user-defined name-value pairs for the specified container. + * @param options The options parameters. + */ + setMetadata(options) { + return this.client.sendOperationRequest({ options }, setMetadataOperationSpec$1); + } + /** + * gets the permissions for the specified container. The permissions indicate whether container data + * may be accessed publicly. + * @param options The options parameters. + */ + getAccessPolicy(options) { + return this.client.sendOperationRequest({ options }, getAccessPolicyOperationSpec); + } + /** + * sets the permissions for the specified container. The permissions indicate whether blobs in a + * container may be accessed publicly. + * @param options The options parameters. + */ + setAccessPolicy(options) { + return this.client.sendOperationRequest({ options }, setAccessPolicyOperationSpec); + } + /** + * Restores a previously-deleted container. + * @param options The options parameters. + */ + restore(options) { + return this.client.sendOperationRequest({ options }, restoreOperationSpec); + } + /** + * Renames an existing container. + * @param sourceContainerName Required. Specifies the name of the container to rename. + * @param options The options parameters. + */ + rename(sourceContainerName2, options) { + return this.client.sendOperationRequest({ sourceContainerName: sourceContainerName2, options }, renameOperationSpec); + } + /** + * The Batch operation allows multiple API calls to be embedded into a single HTTP request. + * @param contentLength The length of the request. + * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch + * boundary. Example header value: multipart/mixed; boundary=batch_ + * @param body Initial data + * @param options The options parameters. + */ + submitBatch(contentLength2, multipartContentType2, body2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, multipartContentType: multipartContentType2, body: body2, options }, submitBatchOperationSpec); + } + /** + * The Filter Blobs operation enables callers to list blobs in a container whose tags match a given + * search expression. Filter blobs searches within the given container. + * @param options The options parameters. + */ + filterBlobs(options) { + return this.client.sendOperationRequest({ options }, filterBlobsOperationSpec); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param options The options parameters. + */ + acquireLease(options) { + return this.client.sendOperationRequest({ options }, acquireLeaseOperationSpec$1); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param leaseId Specifies the current lease ID on the resource. + * @param options The options parameters. + */ + releaseLease(leaseId2, options) { + return this.client.sendOperationRequest({ leaseId: leaseId2, options }, releaseLeaseOperationSpec$1); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param leaseId Specifies the current lease ID on the resource. + * @param options The options parameters. + */ + renewLease(leaseId2, options) { + return this.client.sendOperationRequest({ leaseId: leaseId2, options }, renewLeaseOperationSpec$1); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param options The options parameters. + */ + breakLease(options) { + return this.client.sendOperationRequest({ options }, breakLeaseOperationSpec$1); + } + /** + * [Update] establishes and manages a lock on a container for delete operations. The lock duration can + * be 15 to 60 seconds, or can be infinite + * @param leaseId Specifies the current lease ID on the resource. + * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 + * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor + * (String) for a list of valid GUID string formats. + * @param options The options parameters. + */ + changeLease(leaseId2, proposedLeaseId2, options) { + return this.client.sendOperationRequest({ leaseId: leaseId2, proposedLeaseId: proposedLeaseId2, options }, changeLeaseOperationSpec$1); + } + /** + * [Update] The List Blobs operation returns a list of the blobs under the specified container + * @param options The options parameters. + */ + listBlobFlatSegment(options) { + return this.client.sendOperationRequest({ options }, listBlobFlatSegmentOperationSpec); + } + /** + * [Update] The List Blobs operation returns a list of the blobs under the specified container + * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix + * element in the response body that acts as a placeholder for all blobs whose names begin with the + * same substring up to the appearance of the delimiter character. The delimiter may be a single + * character or a string. + * @param options The options parameters. + */ + listBlobHierarchySegment(delimiter2, options) { + return this.client.sendOperationRequest({ delimiter: delimiter2, options }, listBlobHierarchySegmentOperationSpec); + } + /** + * Returns the sku name and account kind + * @param options The options parameters. + */ + getAccountInfo(options) { + return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec$1); + } + }; + var xmlSerializer$4 = coreClient__namespace.createSerializer( + Mappers, + /* isXml */ + true + ); + var createOperationSpec$2 = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: ContainerCreateHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerCreateExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, restype2], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + metadata, + access2, + defaultEncryptionScope, + preventEncryptionScopeOverride + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var getPropertiesOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + headersMapper: ContainerGetPropertiesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerGetPropertiesExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, restype2], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var deleteOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "DELETE", + responses: { + 202: { + headersMapper: ContainerDeleteHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerDeleteExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, restype2], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var setMetadataOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: ContainerSetMetadataHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerSetMetadataExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp6 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + metadata, + leaseId, + ifModifiedSince + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var getAccessPolicyOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: { + type: { + name: "Sequence", + element: { + type: { name: "Composite", className: "SignedIdentifier" } + } + }, + serializedName: "SignedIdentifiers", + xmlName: "SignedIdentifiers", + xmlIsWrapped: true, + xmlElementName: "SignedIdentifier" + }, + headersMapper: ContainerGetAccessPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerGetAccessPolicyExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp7 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var setAccessPolicyOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: ContainerSetAccessPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerSetAccessPolicyExceptionHeaders + } + }, + requestBody: containerAcl, + queryParameters: [ + timeoutInSeconds, + restype2, + comp7 + ], + urlParameters: [url], + headerParameters: [ + contentType, + accept, + version, + requestId, + access2, + leaseId, + ifModifiedSince, + ifUnmodifiedSince + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer$4 + }; + var restoreOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: ContainerRestoreHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerRestoreExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp8 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + deletedContainerName, + deletedContainerVersion + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var renameOperationSpec = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: ContainerRenameHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerRenameExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp9 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + sourceContainerName, + sourceLeaseId + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var submitBatchOperationSpec = { + path: "/{containerName}", + httpMethod: "POST", + responses: { + 202: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: ContainerSubmitBatchHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerSubmitBatchExceptionHeaders + } + }, + requestBody: body, + queryParameters: [ + timeoutInSeconds, + comp4, + restype2 + ], + urlParameters: [url], + headerParameters: [ + accept, + version, + requestId, + contentLength, + multipartContentType + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer$4 + }; + var filterBlobsOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: FilterBlobSegment, + headersMapper: ContainerFilterBlobsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerFilterBlobsExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + marker, + maxPageSize, + comp5, + where, + restype2 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var acquireLeaseOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: ContainerAcquireLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerAcquireLeaseExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp10 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + action, + duration, + proposedLeaseId + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var releaseLeaseOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: ContainerReleaseLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerReleaseLeaseExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp10 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + action1, + leaseId1 + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var renewLeaseOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: ContainerRenewLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerRenewLeaseExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp10 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + leaseId1, + action2 + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var breakLeaseOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: ContainerBreakLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerBreakLeaseExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp10 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + action3, + breakPeriod + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var changeLeaseOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: ContainerChangeLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerChangeLeaseExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + restype2, + comp10 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + leaseId1, + action4, + proposedLeaseId1 + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var listBlobFlatSegmentOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: ListBlobsFlatSegmentResponse, + headersMapper: ContainerListBlobFlatSegmentHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerListBlobFlatSegmentExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + comp2, + prefix, + marker, + maxPageSize, + restype2, + include1 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var listBlobHierarchySegmentOperationSpec = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: ListBlobsHierarchySegmentResponse, + headersMapper: ContainerListBlobHierarchySegmentHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerListBlobHierarchySegmentExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + comp2, + prefix, + marker, + maxPageSize, + restype2, + include1, + delimiter + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var getAccountInfoOperationSpec$1 = { + path: "/{containerName}", + httpMethod: "GET", + responses: { + 200: { + headersMapper: ContainerGetAccountInfoHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerGetAccountInfoExceptionHeaders + } + }, + queryParameters: [ + comp, + timeoutInSeconds, + restype1 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$4 + }; + var BlobImpl = class { + /** + * Initialize a new instance of the class Blob class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * The Download operation reads or downloads a blob from the system, including its metadata and + * properties. You can also call Download to read a snapshot. + * @param options The options parameters. + */ + download(options) { + return this.client.sendOperationRequest({ options }, downloadOperationSpec); + } + /** + * The Get Properties operation returns all user-defined metadata, standard HTTP properties, and system + * properties for the blob. It does not return the content of the blob. + * @param options The options parameters. + */ + getProperties(options) { + return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec); + } + /** + * If the storage account's soft delete feature is disabled then, when a blob is deleted, it is + * permanently removed from the storage account. If the storage account's soft delete feature is + * enabled, then, when a blob is deleted, it is marked for deletion and becomes inaccessible + * immediately. However, the blob service retains the blob or snapshot for the number of days specified + * by the DeleteRetentionPolicy section of [Storage service properties] + * (Set-Blob-Service-Properties.md). After the specified number of days has passed, the blob's data is + * permanently removed from the storage account. Note that you continue to be charged for the + * soft-deleted blob's storage until it is permanently removed. Use the List Blobs API and specify the + * "include=deleted" query parameter to discover which blobs and snapshots have been soft deleted. You + * can then use the Undelete Blob API to restore a soft-deleted blob. All other operations on a + * soft-deleted blob or snapshot causes the service to return an HTTP status code of 404 + * (ResourceNotFound). + * @param options The options parameters. + */ + delete(options) { + return this.client.sendOperationRequest({ options }, deleteOperationSpec); + } + /** + * Undelete a blob that was previously soft deleted + * @param options The options parameters. + */ + undelete(options) { + return this.client.sendOperationRequest({ options }, undeleteOperationSpec); + } + /** + * Sets the time a blob will expire and be deleted. + * @param expiryOptions Required. Indicates mode of the expiry time + * @param options The options parameters. + */ + setExpiry(expiryOptions2, options) { + return this.client.sendOperationRequest({ expiryOptions: expiryOptions2, options }, setExpiryOperationSpec); + } + /** + * The Set HTTP Headers operation sets system properties on the blob + * @param options The options parameters. + */ + setHttpHeaders(options) { + return this.client.sendOperationRequest({ options }, setHttpHeadersOperationSpec); + } + /** + * The Set Immutability Policy operation sets the immutability policy on the blob + * @param options The options parameters. + */ + setImmutabilityPolicy(options) { + return this.client.sendOperationRequest({ options }, setImmutabilityPolicyOperationSpec); + } + /** + * The Delete Immutability Policy operation deletes the immutability policy on the blob + * @param options The options parameters. + */ + deleteImmutabilityPolicy(options) { + return this.client.sendOperationRequest({ options }, deleteImmutabilityPolicyOperationSpec); + } + /** + * The Set Legal Hold operation sets a legal hold on the blob. + * @param legalHold Specified if a legal hold should be set on the blob. + * @param options The options parameters. + */ + setLegalHold(legalHold2, options) { + return this.client.sendOperationRequest({ legalHold: legalHold2, options }, setLegalHoldOperationSpec); + } + /** + * The Set Blob Metadata operation sets user-defined metadata for the specified blob as one or more + * name-value pairs + * @param options The options parameters. + */ + setMetadata(options) { + return this.client.sendOperationRequest({ options }, setMetadataOperationSpec); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param options The options parameters. + */ + acquireLease(options) { + return this.client.sendOperationRequest({ options }, acquireLeaseOperationSpec); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param leaseId Specifies the current lease ID on the resource. + * @param options The options parameters. + */ + releaseLease(leaseId2, options) { + return this.client.sendOperationRequest({ leaseId: leaseId2, options }, releaseLeaseOperationSpec); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param leaseId Specifies the current lease ID on the resource. + * @param options The options parameters. + */ + renewLease(leaseId2, options) { + return this.client.sendOperationRequest({ leaseId: leaseId2, options }, renewLeaseOperationSpec); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param leaseId Specifies the current lease ID on the resource. + * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 + * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor + * (String) for a list of valid GUID string formats. + * @param options The options parameters. + */ + changeLease(leaseId2, proposedLeaseId2, options) { + return this.client.sendOperationRequest({ leaseId: leaseId2, proposedLeaseId: proposedLeaseId2, options }, changeLeaseOperationSpec); + } + /** + * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete + * operations + * @param options The options parameters. + */ + breakLease(options) { + return this.client.sendOperationRequest({ options }, breakLeaseOperationSpec); + } + /** + * The Create Snapshot operation creates a read-only snapshot of a blob + * @param options The options parameters. + */ + createSnapshot(options) { + return this.client.sendOperationRequest({ options }, createSnapshotOperationSpec); + } + /** + * The Start Copy From URL operation copies a blob or an internet resource to a new blob. + * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to + * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would + * appear in a request URI. The source blob must either be public or must be authenticated via a shared + * access signature. + * @param options The options parameters. + */ + startCopyFromURL(copySource2, options) { + return this.client.sendOperationRequest({ copySource: copySource2, options }, startCopyFromURLOperationSpec); + } + /** + * The Copy From URL operation copies a blob or an internet resource to a new blob. It will not return + * a response until the copy is complete. + * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to + * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would + * appear in a request URI. The source blob must either be public or must be authenticated via a shared + * access signature. + * @param options The options parameters. + */ + copyFromURL(copySource2, options) { + return this.client.sendOperationRequest({ copySource: copySource2, options }, copyFromURLOperationSpec); + } + /** + * The Abort Copy From URL operation aborts a pending Copy From URL operation, and leaves a destination + * blob with zero length and full metadata. + * @param copyId The copy identifier provided in the x-ms-copy-id header of the original Copy Blob + * operation. + * @param options The options parameters. + */ + abortCopyFromURL(copyId2, options) { + return this.client.sendOperationRequest({ copyId: copyId2, options }, abortCopyFromURLOperationSpec); + } + /** + * The Set Tier operation sets the tier on a blob. The operation is allowed on a page blob in a premium + * storage account and on a block blob in a blob storage account (locally redundant storage only). A + * premium page blob's tier determines the allowed size, IOPS, and bandwidth of the blob. A block + * blob's tier determines Hot/Cool/Archive storage type. This operation does not update the blob's + * ETag. + * @param tier Indicates the tier to be set on the blob. + * @param options The options parameters. + */ + setTier(tier2, options) { + return this.client.sendOperationRequest({ tier: tier2, options }, setTierOperationSpec); + } + /** + * Returns the sku name and account kind + * @param options The options parameters. + */ + getAccountInfo(options) { + return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec); + } + /** + * The Query operation enables users to select/project on blob data by providing simple query + * expressions. + * @param options The options parameters. + */ + query(options) { + return this.client.sendOperationRequest({ options }, queryOperationSpec); + } + /** + * The Get Tags operation enables users to get the tags associated with a blob. + * @param options The options parameters. + */ + getTags(options) { + return this.client.sendOperationRequest({ options }, getTagsOperationSpec); + } + /** + * The Set Tags operation enables users to set tags on a blob. + * @param options The options parameters. + */ + setTags(options) { + return this.client.sendOperationRequest({ options }, setTagsOperationSpec); + } + }; + var xmlSerializer$3 = coreClient__namespace.createSerializer( + Mappers, + /* isXml */ + true + ); + var downloadOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: BlobDownloadHeaders + }, + 206: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: BlobDownloadHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobDownloadExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + snapshot, + versionId + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + range, + rangeGetContentMD5, + rangeGetContentCRC64, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var getPropertiesOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "HEAD", + responses: { + 200: { + headersMapper: BlobGetPropertiesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobGetPropertiesExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + snapshot, + versionId + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var deleteOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "DELETE", + responses: { + 202: { + headersMapper: BlobDeleteHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobDeleteExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + snapshot, + versionId, + blobDeleteType + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + deleteSnapshots + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var undeleteOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobUndeleteHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobUndeleteExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp8], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var setExpiryOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetExpiryHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetExpiryExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp11], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + expiryOptions, + expiresOn + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var setHttpHeadersOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetHttpHeadersHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetHttpHeadersExceptionHeaders + } + }, + queryParameters: [comp, timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + blobCacheControl, + blobContentType, + blobContentMD5, + blobContentEncoding, + blobContentLanguage, + blobContentDisposition + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var setImmutabilityPolicyOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetImmutabilityPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetImmutabilityPolicyExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp12], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifUnmodifiedSince, + immutabilityPolicyExpiry, + immutabilityPolicyMode + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var deleteImmutabilityPolicyOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "DELETE", + responses: { + 200: { + headersMapper: BlobDeleteImmutabilityPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobDeleteImmutabilityPolicyExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp12], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var setLegalHoldOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetLegalHoldHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetLegalHoldExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp13], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + legalHold + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var setMetadataOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetMetadataHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetMetadataExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp6], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + encryptionScope + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var acquireLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: BlobAcquireLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobAcquireLeaseExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp10], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + action, + duration, + proposedLeaseId, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var releaseLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobReleaseLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobReleaseLeaseExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp10], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + action1, + leaseId1, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var renewLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobRenewLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobRenewLeaseExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp10], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + leaseId1, + action2, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var changeLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobChangeLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobChangeLeaseExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp10], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + leaseId1, + action4, + proposedLeaseId1, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var breakLeaseOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: BlobBreakLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobBreakLeaseExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp10], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + action3, + breakPeriod, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var createSnapshotOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: BlobCreateSnapshotHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobCreateSnapshotExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp14], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + encryptionScope + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var startCopyFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: BlobStartCopyFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobStartCopyFromURLExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + tier, + rehydratePriority, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + sourceIfTags, + copySource, + blobTagsString, + sealBlob, + legalHold1 + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var copyFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: BlobCopyFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobCopyFromURLExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + encryptionScope, + tier, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + copySource, + blobTagsString, + legalHold1, + xMsRequiresSync, + sourceContentMD5, + copySourceAuthorization, + copySourceTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var abortCopyFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 204: { + headersMapper: BlobAbortCopyFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobAbortCopyFromURLExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + comp15, + copyId + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + copyActionAbortConstant + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var setTierOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetTierHeaders + }, + 202: { + headersMapper: BlobSetTierHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetTierExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + snapshot, + versionId, + comp16 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifTags, + rehydratePriority, + tier1 + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var getAccountInfoOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + headersMapper: BlobGetAccountInfoHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobGetAccountInfoExceptionHeaders + } + }, + queryParameters: [ + comp, + timeoutInSeconds, + restype1 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var queryOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: BlobQueryHeaders + }, + 206: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: BlobQueryHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobQueryExceptionHeaders + } + }, + requestBody: queryRequest, + queryParameters: [ + timeoutInSeconds, + snapshot, + comp17 + ], + urlParameters: [url], + headerParameters: [ + contentType, + accept, + version, + requestId, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer$3 + }; + var getTagsOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: BlobTags, + headersMapper: BlobGetTagsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobGetTagsExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + snapshot, + versionId, + comp18 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifTags + ], + isXML: true, + serializer: xmlSerializer$3 + }; + var setTagsOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 204: { + headersMapper: BlobSetTagsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetTagsExceptionHeaders + } + }, + requestBody: tags, + queryParameters: [ + timeoutInSeconds, + versionId, + comp18 + ], + urlParameters: [url], + headerParameters: [ + contentType, + accept, + version, + requestId, + leaseId, + ifTags, + transactionalContentMD5, + transactionalContentCrc64 + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer$3 + }; + var PageBlobImpl = class { + /** + * Initialize a new instance of the class PageBlob class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * The Create operation creates a new page blob. + * @param contentLength The length of the request. + * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The + * page blob size must be aligned to a 512-byte boundary. + * @param options The options parameters. + */ + create(contentLength2, blobContentLength2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, blobContentLength: blobContentLength2, options }, createOperationSpec$1); + } + /** + * The Upload Pages operation writes a range of pages to a page blob + * @param contentLength The length of the request. + * @param body Initial data + * @param options The options parameters. + */ + uploadPages(contentLength2, body2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, body: body2, options }, uploadPagesOperationSpec); + } + /** + * The Clear Pages operation clears a set of pages from a page blob + * @param contentLength The length of the request. + * @param options The options parameters. + */ + clearPages(contentLength2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, options }, clearPagesOperationSpec); + } + /** + * The Upload Pages operation writes a range of pages to a page blob where the contents are read from a + * URL + * @param sourceUrl Specify a URL to the copy source. + * @param sourceRange Bytes of source data in the specified range. The length of this range should + * match the ContentLength header and x-ms-range/Range destination range header. + * @param contentLength The length of the request. + * @param range The range of bytes to which the source range would be written. The range should be 512 + * aligned and range-end is required. + * @param options The options parameters. + */ + uploadPagesFromURL(sourceUrl2, sourceRange2, contentLength2, range2, options) { + return this.client.sendOperationRequest({ sourceUrl: sourceUrl2, sourceRange: sourceRange2, contentLength: contentLength2, range: range2, options }, uploadPagesFromURLOperationSpec); + } + /** + * The Get Page Ranges operation returns the list of valid page ranges for a page blob or snapshot of a + * page blob + * @param options The options parameters. + */ + getPageRanges(options) { + return this.client.sendOperationRequest({ options }, getPageRangesOperationSpec); + } + /** + * The Get Page Ranges Diff operation returns the list of valid page ranges for a page blob that were + * changed between target blob and previous snapshot. + * @param options The options parameters. + */ + getPageRangesDiff(options) { + return this.client.sendOperationRequest({ options }, getPageRangesDiffOperationSpec); + } + /** + * Resize the Blob + * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The + * page blob size must be aligned to a 512-byte boundary. + * @param options The options parameters. + */ + resize(blobContentLength2, options) { + return this.client.sendOperationRequest({ blobContentLength: blobContentLength2, options }, resizeOperationSpec); + } + /** + * Update the sequence number of the blob + * @param sequenceNumberAction Required if the x-ms-blob-sequence-number header is set for the request. + * This property applies to page blobs only. This property indicates how the service should modify the + * blob's sequence number + * @param options The options parameters. + */ + updateSequenceNumber(sequenceNumberAction2, options) { + return this.client.sendOperationRequest({ sequenceNumberAction: sequenceNumberAction2, options }, updateSequenceNumberOperationSpec); + } + /** + * The Copy Incremental operation copies a snapshot of the source page blob to a destination page blob. + * The snapshot is copied such that only the differential changes between the previously copied + * snapshot are transferred to the destination. The copied snapshots are complete copies of the + * original snapshot and can be read or copied from as usual. This API is supported since REST version + * 2016-05-31. + * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to + * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would + * appear in a request URI. The source blob must either be public or must be authenticated via a shared + * access signature. + * @param options The options parameters. + */ + copyIncremental(copySource2, options) { + return this.client.sendOperationRequest({ copySource: copySource2, options }, copyIncrementalOperationSpec); + } + }; + var xmlSerializer$2 = coreClient__namespace.createSerializer( + Mappers, + /* isXml */ + true + ); + var createOperationSpec$1 = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: PageBlobCreateHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobCreateExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + contentLength, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + blobCacheControl, + blobContentType, + blobContentMD5, + blobContentEncoding, + blobContentLanguage, + blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + encryptionScope, + tier, + blobTagsString, + legalHold1, + blobType, + blobContentLength, + blobSequenceNumber + ], + isXML: true, + serializer: xmlSerializer$2 + }; + var uploadPagesOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: PageBlobUploadPagesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobUploadPagesExceptionHeaders + } + }, + requestBody: body1, + queryParameters: [timeoutInSeconds, comp19], + urlParameters: [url], + headerParameters: [ + version, + requestId, + contentLength, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + range, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + encryptionScope, + transactionalContentMD5, + transactionalContentCrc64, + contentType1, + accept2, + pageWrite, + ifSequenceNumberLessThanOrEqualTo, + ifSequenceNumberLessThan, + ifSequenceNumberEqualTo + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "binary", + serializer: xmlSerializer$2 + }; + var clearPagesOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: PageBlobClearPagesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobClearPagesExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp19], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + contentLength, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + range, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + encryptionScope, + ifSequenceNumberLessThanOrEqualTo, + ifSequenceNumberLessThan, + ifSequenceNumberEqualTo, + pageWrite1 + ], + isXML: true, + serializer: xmlSerializer$2 + }; + var uploadPagesFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: PageBlobUploadPagesFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobUploadPagesFromURLExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp19], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + contentLength, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + encryptionScope, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + sourceContentMD5, + copySourceAuthorization, + pageWrite, + ifSequenceNumberLessThanOrEqualTo, + ifSequenceNumberLessThan, + ifSequenceNumberEqualTo, + sourceUrl, + sourceRange, + sourceContentCrc64, + range1 + ], + isXML: true, + serializer: xmlSerializer$2 + }; + var getPageRangesOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: PageList, + headersMapper: PageBlobGetPageRangesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobGetPageRangesExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + marker, + maxPageSize, + snapshot, + comp20 + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + range, + ifMatch, + ifNoneMatch, + ifTags + ], + isXML: true, + serializer: xmlSerializer$2 + }; + var getPageRangesDiffOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: PageList, + headersMapper: PageBlobGetPageRangesDiffHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobGetPageRangesDiffExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + marker, + maxPageSize, + snapshot, + comp20, + prevsnapshot + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + range, + ifMatch, + ifNoneMatch, + ifTags, + prevSnapshotUrl + ], + isXML: true, + serializer: xmlSerializer$2 + }; + var resizeOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: PageBlobResizeHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobResizeExceptionHeaders + } + }, + queryParameters: [comp, timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + encryptionScope, + blobContentLength + ], + isXML: true, + serializer: xmlSerializer$2 + }; + var updateSequenceNumberOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: PageBlobUpdateSequenceNumberHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobUpdateSequenceNumberExceptionHeaders + } + }, + queryParameters: [comp, timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + blobSequenceNumber, + sequenceNumberAction + ], + isXML: true, + serializer: xmlSerializer$2 + }; + var copyIncrementalOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 202: { + headersMapper: PageBlobCopyIncrementalHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobCopyIncrementalExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp21], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + copySource + ], + isXML: true, + serializer: xmlSerializer$2 + }; + var AppendBlobImpl = class { + /** + * Initialize a new instance of the class AppendBlob class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * The Create Append Blob operation creates a new append blob. + * @param contentLength The length of the request. + * @param options The options parameters. + */ + create(contentLength2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, options }, createOperationSpec); + } + /** + * The Append Block operation commits a new block of data to the end of an existing append blob. The + * Append Block operation is permitted only if the blob was created with x-ms-blob-type set to + * AppendBlob. Append Block is supported only on version 2015-02-21 version or later. + * @param contentLength The length of the request. + * @param body Initial data + * @param options The options parameters. + */ + appendBlock(contentLength2, body2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, body: body2, options }, appendBlockOperationSpec); + } + /** + * The Append Block operation commits a new block of data to the end of an existing append blob where + * the contents are read from a source url. The Append Block operation is permitted only if the blob + * was created with x-ms-blob-type set to AppendBlob. Append Block is supported only on version + * 2015-02-21 version or later. + * @param sourceUrl Specify a URL to the copy source. + * @param contentLength The length of the request. + * @param options The options parameters. + */ + appendBlockFromUrl(sourceUrl2, contentLength2, options) { + return this.client.sendOperationRequest({ sourceUrl: sourceUrl2, contentLength: contentLength2, options }, appendBlockFromUrlOperationSpec); + } + /** + * The Seal operation seals the Append Blob to make it read-only. Seal is supported only on version + * 2019-12-12 version or later. + * @param options The options parameters. + */ + seal(options) { + return this.client.sendOperationRequest({ options }, sealOperationSpec); + } + }; + var xmlSerializer$1 = coreClient__namespace.createSerializer( + Mappers, + /* isXml */ + true + ); + var createOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: AppendBlobCreateHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: AppendBlobCreateExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + contentLength, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + blobCacheControl, + blobContentType, + blobContentMD5, + blobContentEncoding, + blobContentLanguage, + blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + encryptionScope, + blobTagsString, + legalHold1, + blobType1 + ], + isXML: true, + serializer: xmlSerializer$1 + }; + var appendBlockOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: AppendBlobAppendBlockHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: AppendBlobAppendBlockExceptionHeaders + } + }, + requestBody: body1, + queryParameters: [timeoutInSeconds, comp22], + urlParameters: [url], + headerParameters: [ + version, + requestId, + contentLength, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + encryptionScope, + transactionalContentMD5, + transactionalContentCrc64, + contentType1, + accept2, + maxSize, + appendPosition + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "binary", + serializer: xmlSerializer$1 + }; + var appendBlockFromUrlOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: AppendBlobAppendBlockFromUrlHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: AppendBlobAppendBlockFromUrlExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp22], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + contentLength, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + encryptionScope, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + sourceContentMD5, + copySourceAuthorization, + transactionalContentMD5, + sourceUrl, + sourceContentCrc64, + maxSize, + appendPosition, + sourceRange1 + ], + isXML: true, + serializer: xmlSerializer$1 + }; + var sealOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: AppendBlobSealHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: AppendBlobSealExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp23], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + appendPosition + ], + isXML: true, + serializer: xmlSerializer$1 + }; + var BlockBlobImpl = class { + /** + * Initialize a new instance of the class BlockBlob class. + * @param client Reference to the service client + */ + constructor(client) { + this.client = client; + } + /** + * The Upload Block Blob operation updates the content of an existing block blob. Updating an existing + * block blob overwrites any existing metadata on the blob. Partial updates are not supported with Put + * Blob; the content of the existing blob is overwritten with the content of the new blob. To perform a + * partial update of the content of a block blob, use the Put Block List operation. + * @param contentLength The length of the request. + * @param body Initial data + * @param options The options parameters. + */ + upload(contentLength2, body2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, body: body2, options }, uploadOperationSpec); + } + /** + * The Put Blob from URL operation creates a new Block Blob where the contents of the blob are read + * from a given URL. This API is supported beginning with the 2020-04-08 version. Partial updates are + * not supported with Put Blob from URL; the content of an existing blob is overwritten with the + * content of the new blob. To perform partial updates to a block blob’s contents using a source URL, + * use the Put Block from URL API in conjunction with Put Block List. + * @param contentLength The length of the request. + * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to + * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would + * appear in a request URI. The source blob must either be public or must be authenticated via a shared + * access signature. + * @param options The options parameters. + */ + putBlobFromUrl(contentLength2, copySource2, options) { + return this.client.sendOperationRequest({ contentLength: contentLength2, copySource: copySource2, options }, putBlobFromUrlOperationSpec); + } + /** + * The Stage Block operation creates a new block to be committed as part of a blob + * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string + * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified + * for the blockid parameter must be the same size for each block. + * @param contentLength The length of the request. + * @param body Initial data + * @param options The options parameters. + */ + stageBlock(blockId2, contentLength2, body2, options) { + return this.client.sendOperationRequest({ blockId: blockId2, contentLength: contentLength2, body: body2, options }, stageBlockOperationSpec); + } + /** + * The Stage Block operation creates a new block to be committed as part of a blob where the contents + * are read from a URL. + * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string + * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified + * for the blockid parameter must be the same size for each block. + * @param contentLength The length of the request. + * @param sourceUrl Specify a URL to the copy source. + * @param options The options parameters. + */ + stageBlockFromURL(blockId2, contentLength2, sourceUrl2, options) { + return this.client.sendOperationRequest({ blockId: blockId2, contentLength: contentLength2, sourceUrl: sourceUrl2, options }, stageBlockFromURLOperationSpec); + } + /** + * The Commit Block List operation writes a blob by specifying the list of block IDs that make up the + * blob. In order to be written as part of a blob, a block must have been successfully written to the + * server in a prior Put Block operation. You can call Put Block List to update a blob by uploading + * only those blocks that have changed, then committing the new and existing blocks together. You can + * do this by specifying whether to commit a block from the committed block list or from the + * uncommitted block list, or to commit the most recently uploaded version of the block, whichever list + * it may belong to. + * @param blocks Blob Blocks. + * @param options The options parameters. + */ + commitBlockList(blocks2, options) { + return this.client.sendOperationRequest({ blocks: blocks2, options }, commitBlockListOperationSpec); + } + /** + * The Get Block List operation retrieves the list of blocks that have been uploaded as part of a block + * blob + * @param listType Specifies whether to return the list of committed blocks, the list of uncommitted + * blocks, or both lists together. + * @param options The options parameters. + */ + getBlockList(listType2, options) { + return this.client.sendOperationRequest({ listType: listType2, options }, getBlockListOperationSpec); + } + }; + var xmlSerializer = coreClient__namespace.createSerializer( + Mappers, + /* isXml */ + true + ); + var uploadOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: BlockBlobUploadHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobUploadExceptionHeaders + } + }, + requestBody: body1, + queryParameters: [timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + contentLength, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + blobCacheControl, + blobContentType, + blobContentMD5, + blobContentEncoding, + blobContentLanguage, + blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + encryptionScope, + tier, + blobTagsString, + legalHold1, + transactionalContentMD5, + transactionalContentCrc64, + contentType1, + accept2, + blobType2 + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "binary", + serializer: xmlSerializer + }; + var putBlobFromUrlOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: BlockBlobPutBlobFromUrlHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobPutBlobFromUrlExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + contentLength, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + blobCacheControl, + blobContentType, + blobContentMD5, + blobContentEncoding, + blobContentLanguage, + blobContentDisposition, + encryptionScope, + tier, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + sourceIfTags, + copySource, + blobTagsString, + sourceContentMD5, + copySourceAuthorization, + copySourceTags, + transactionalContentMD5, + blobType2, + copySourceBlobProperties + ], + isXML: true, + serializer: xmlSerializer + }; + var stageBlockOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: BlockBlobStageBlockHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobStageBlockExceptionHeaders + } + }, + requestBody: body1, + queryParameters: [ + timeoutInSeconds, + comp24, + blockId + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + contentLength, + leaseId, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + encryptionScope, + transactionalContentMD5, + transactionalContentCrc64, + contentType1, + accept2 + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "binary", + serializer: xmlSerializer + }; + var stageBlockFromURLOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: BlockBlobStageBlockFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobStageBlockFromURLExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + comp24, + blockId + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + contentLength, + leaseId, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + encryptionScope, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + sourceContentMD5, + copySourceAuthorization, + sourceUrl, + sourceContentCrc64, + sourceRange1 + ], + isXML: true, + serializer: xmlSerializer + }; + var commitBlockListOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 201: { + headersMapper: BlockBlobCommitBlockListHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobCommitBlockListExceptionHeaders + } + }, + requestBody: blocks, + queryParameters: [timeoutInSeconds, comp25], + urlParameters: [url], + headerParameters: [ + contentType, + accept, + version, + requestId, + metadata, + leaseId, + ifModifiedSince, + ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifMatch, + ifNoneMatch, + ifTags, + blobCacheControl, + blobContentType, + blobContentMD5, + blobContentEncoding, + blobContentLanguage, + blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + encryptionScope, + tier, + blobTagsString, + legalHold1, + transactionalContentMD5, + transactionalContentCrc64 + ], + isXML: true, + contentType: "application/xml; charset=utf-8", + mediaType: "xml", + serializer: xmlSerializer + }; + var getBlockListOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: BlockList, + headersMapper: BlockBlobGetBlockListHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobGetBlockListExceptionHeaders + } + }, + queryParameters: [ + timeoutInSeconds, + snapshot, + comp25, + listType + ], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + leaseId, + ifTags + ], + isXML: true, + serializer: xmlSerializer + }; + var StorageClient$1 = class StorageClient extends coreHttpCompat__namespace.ExtendedServiceClient { + /** + * Initializes a new instance of the StorageClient class. + * @param url The URL of the service account, container, or blob that is the target of the desired + * operation. + * @param options The parameter options + */ + constructor(url2, options) { + var _a, _b; + if (url2 === void 0) { + throw new Error("'url' cannot be null"); + } + if (!options) { + options = {}; + } + const defaults = { + requestContentType: "application/json; charset=utf-8" + }; + const packageDetails = `azsdk-js-azure-storage-blob/12.25.0`; + const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; + const optionsWithDefaults = Object.assign(Object.assign(Object.assign({}, defaults), options), { userAgentOptions: { + userAgentPrefix + }, endpoint: (_b = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri) !== null && _b !== void 0 ? _b : "{url}" }); + super(optionsWithDefaults); + this.url = url2; + this.version = options.version || "2024-11-04"; + this.service = new ServiceImpl(this); + this.container = new ContainerImpl(this); + this.blob = new BlobImpl(this); + this.pageBlob = new PageBlobImpl(this); + this.appendBlob = new AppendBlobImpl(this); + this.blockBlob = new BlockBlobImpl(this); + } + }; + var StorageContextClient = class extends StorageClient$1 { + async sendOperationRequest(operationArguments, operationSpec) { + const operationSpecToSend = Object.assign({}, operationSpec); + if (operationSpecToSend.path === "/{containerName}" || operationSpecToSend.path === "/{containerName}/{blob}") { + operationSpecToSend.path = ""; + } + return super.sendOperationRequest(operationArguments, operationSpecToSend); + } + }; + var StorageClient = class { + /** + * Creates an instance of StorageClient. + * @param url - url to resource + * @param pipeline - request policy pipeline. + */ + constructor(url2, pipeline) { + this.url = escapeURLPath(url2); + this.accountName = getAccountNameFromUrl(url2); + this.pipeline = pipeline; + this.storageClientContext = new StorageContextClient(this.url, getCoreClientOptions(pipeline)); + this.isHttps = iEqual(getURLScheme(this.url) || "", "https"); + this.credential = getCredentialFromPipeline(pipeline); + const storageClientContext = this.storageClientContext; + storageClientContext.requestContentType = void 0; + } + }; + var tracingClient = coreTracing.createTracingClient({ + packageName: "@azure/storage-blob", + packageVersion: SDK_VERSION, + namespace: "Microsoft.Storage" + }); + var BlobSASPermissions = class _BlobSASPermissions { + constructor() { + this.read = false; + this.add = false; + this.create = false; + this.write = false; + this.delete = false; + this.deleteVersion = false; + this.tag = false; + this.move = false; + this.execute = false; + this.setImmutabilityPolicy = false; + this.permanentDelete = false; + } + /** + * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. + * + * @param permissions - + */ + static parse(permissions) { + const blobSASPermissions = new _BlobSASPermissions(); + for (const char of permissions) { + switch (char) { + case "r": + blobSASPermissions.read = true; + break; + case "a": + blobSASPermissions.add = true; + break; + case "c": + blobSASPermissions.create = true; + break; + case "w": + blobSASPermissions.write = true; + break; + case "d": + blobSASPermissions.delete = true; + break; + case "x": + blobSASPermissions.deleteVersion = true; + break; + case "t": + blobSASPermissions.tag = true; + break; + case "m": + blobSASPermissions.move = true; + break; + case "e": + blobSASPermissions.execute = true; + break; + case "i": + blobSASPermissions.setImmutabilityPolicy = true; + break; + case "y": + blobSASPermissions.permanentDelete = true; + break; + default: + throw new RangeError(`Invalid permission: ${char}`); + } + } + return blobSASPermissions; + } + /** + * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. + * + * @param permissionLike - + */ + static from(permissionLike) { + const blobSASPermissions = new _BlobSASPermissions(); + if (permissionLike.read) { + blobSASPermissions.read = true; + } + if (permissionLike.add) { + blobSASPermissions.add = true; + } + if (permissionLike.create) { + blobSASPermissions.create = true; + } + if (permissionLike.write) { + blobSASPermissions.write = true; + } + if (permissionLike.delete) { + blobSASPermissions.delete = true; + } + if (permissionLike.deleteVersion) { + blobSASPermissions.deleteVersion = true; + } + if (permissionLike.tag) { + blobSASPermissions.tag = true; + } + if (permissionLike.move) { + blobSASPermissions.move = true; + } + if (permissionLike.execute) { + blobSASPermissions.execute = true; + } + if (permissionLike.setImmutabilityPolicy) { + blobSASPermissions.setImmutabilityPolicy = true; + } + if (permissionLike.permanentDelete) { + blobSASPermissions.permanentDelete = true; + } + return blobSASPermissions; + } + /** + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. + * + * @returns A string which represents the BlobSASPermissions + */ + toString() { + const permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.move) { + permissions.push("m"); + } + if (this.execute) { + permissions.push("e"); + } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } + if (this.permanentDelete) { + permissions.push("y"); + } + return permissions.join(""); + } + }; + var ContainerSASPermissions = class _ContainerSASPermissions { + constructor() { + this.read = false; + this.add = false; + this.create = false; + this.write = false; + this.delete = false; + this.deleteVersion = false; + this.list = false; + this.tag = false; + this.move = false; + this.execute = false; + this.setImmutabilityPolicy = false; + this.permanentDelete = false; + this.filterByTags = false; + } + /** + * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. + * + * @param permissions - + */ + static parse(permissions) { + const containerSASPermissions = new _ContainerSASPermissions(); + for (const char of permissions) { + switch (char) { + case "r": + containerSASPermissions.read = true; + break; + case "a": + containerSASPermissions.add = true; + break; + case "c": + containerSASPermissions.create = true; + break; + case "w": + containerSASPermissions.write = true; + break; + case "d": + containerSASPermissions.delete = true; + break; + case "l": + containerSASPermissions.list = true; + break; + case "t": + containerSASPermissions.tag = true; + break; + case "x": + containerSASPermissions.deleteVersion = true; + break; + case "m": + containerSASPermissions.move = true; + break; + case "e": + containerSASPermissions.execute = true; + break; + case "i": + containerSASPermissions.setImmutabilityPolicy = true; + break; + case "y": + containerSASPermissions.permanentDelete = true; + break; + case "f": + containerSASPermissions.filterByTags = true; + break; + default: + throw new RangeError(`Invalid permission ${char}`); + } + } + return containerSASPermissions; + } + /** + * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. + * + * @param permissionLike - + */ + static from(permissionLike) { + const containerSASPermissions = new _ContainerSASPermissions(); + if (permissionLike.read) { + containerSASPermissions.read = true; + } + if (permissionLike.add) { + containerSASPermissions.add = true; + } + if (permissionLike.create) { + containerSASPermissions.create = true; + } + if (permissionLike.write) { + containerSASPermissions.write = true; + } + if (permissionLike.delete) { + containerSASPermissions.delete = true; + } + if (permissionLike.list) { + containerSASPermissions.list = true; + } + if (permissionLike.deleteVersion) { + containerSASPermissions.deleteVersion = true; + } + if (permissionLike.tag) { + containerSASPermissions.tag = true; + } + if (permissionLike.move) { + containerSASPermissions.move = true; + } + if (permissionLike.execute) { + containerSASPermissions.execute = true; + } + if (permissionLike.setImmutabilityPolicy) { + containerSASPermissions.setImmutabilityPolicy = true; + } + if (permissionLike.permanentDelete) { + containerSASPermissions.permanentDelete = true; + } + if (permissionLike.filterByTags) { + containerSASPermissions.filterByTags = true; + } + return containerSASPermissions; + } + /** + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. + * + * The order of the characters should be as specified here to ensure correctness. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + */ + toString() { + const permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.list) { + permissions.push("l"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.move) { + permissions.push("m"); + } + if (this.execute) { + permissions.push("e"); + } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } + if (this.permanentDelete) { + permissions.push("y"); + } + if (this.filterByTags) { + permissions.push("f"); + } + return permissions.join(""); + } + }; + var UserDelegationKeyCredential = class { + /** + * Creates an instance of UserDelegationKeyCredential. + * @param accountName - + * @param userDelegationKey - + */ + constructor(accountName, userDelegationKey) { + this.accountName = accountName; + this.userDelegationKey = userDelegationKey; + this.key = Buffer.from(userDelegationKey.value, "base64"); + } + /** + * Generates a hash signature for an HTTP request or for a SAS. + * + * @param stringToSign - + */ + computeHMACSHA256(stringToSign) { + return crypto.createHmac("sha256", this.key).update(stringToSign, "utf8").digest("base64"); + } + }; + function ipRangeToString(ipRange) { + return ipRange.end ? `${ipRange.start}-${ipRange.end}` : ipRange.start; + } + exports2.SASProtocol = void 0; + (function(SASProtocol) { + SASProtocol["Https"] = "https"; + SASProtocol["HttpsAndHttp"] = "https,http"; + })(exports2.SASProtocol || (exports2.SASProtocol = {})); + var SASQueryParameters = class { + /** + * Optional. IP range allowed for this SAS. + * + * @readonly + */ + get ipRange() { + if (this.ipRangeInner) { + return { + end: this.ipRangeInner.end, + start: this.ipRangeInner.start + }; + } + return void 0; + } + constructor(version2, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn2, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType2, userDelegationKey, preauthorizedAgentObjectId, correlationId, encryptionScope2) { + this.version = version2; + this.signature = signature; + if (permissionsOrOptions !== void 0 && typeof permissionsOrOptions !== "string") { + this.permissions = permissionsOrOptions.permissions; + this.services = permissionsOrOptions.services; + this.resourceTypes = permissionsOrOptions.resourceTypes; + this.protocol = permissionsOrOptions.protocol; + this.startsOn = permissionsOrOptions.startsOn; + this.expiresOn = permissionsOrOptions.expiresOn; + this.ipRangeInner = permissionsOrOptions.ipRange; + this.identifier = permissionsOrOptions.identifier; + this.encryptionScope = permissionsOrOptions.encryptionScope; + this.resource = permissionsOrOptions.resource; + this.cacheControl = permissionsOrOptions.cacheControl; + this.contentDisposition = permissionsOrOptions.contentDisposition; + this.contentEncoding = permissionsOrOptions.contentEncoding; + this.contentLanguage = permissionsOrOptions.contentLanguage; + this.contentType = permissionsOrOptions.contentType; + if (permissionsOrOptions.userDelegationKey) { + this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; + this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; + this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; + this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; + this.signedService = permissionsOrOptions.userDelegationKey.signedService; + this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; + this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; + this.correlationId = permissionsOrOptions.correlationId; + } + } else { + this.services = services; + this.resourceTypes = resourceTypes; + this.expiresOn = expiresOn2; + this.permissions = permissionsOrOptions; + this.protocol = protocol; + this.startsOn = startsOn; + this.ipRangeInner = ipRange; + this.encryptionScope = encryptionScope2; + this.identifier = identifier; + this.resource = resource; + this.cacheControl = cacheControl; + this.contentDisposition = contentDisposition; + this.contentEncoding = contentEncoding; + this.contentLanguage = contentLanguage; + this.contentType = contentType2; + if (userDelegationKey) { + this.signedOid = userDelegationKey.signedObjectId; + this.signedTenantId = userDelegationKey.signedTenantId; + this.signedStartsOn = userDelegationKey.signedStartsOn; + this.signedExpiresOn = userDelegationKey.signedExpiresOn; + this.signedService = userDelegationKey.signedService; + this.signedVersion = userDelegationKey.signedVersion; + this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; + this.correlationId = correlationId; + } + } + } + /** + * Encodes all SAS query parameters into a string that can be appended to a URL. + * + */ + toString() { + const params = [ + "sv", + "ss", + "srt", + "spr", + "st", + "se", + "sip", + "si", + "ses", + "skoid", + // Signed object ID + "sktid", + // Signed tenant ID + "skt", + // Signed key start time + "ske", + // Signed key expiry time + "sks", + // Signed key service + "skv", + // Signed key version + "sr", + "sp", + "sig", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct", + "saoid", + "scid" + ]; + const queries = []; + for (const param of params) { + switch (param) { + case "sv": + this.tryAppendQueryParameter(queries, param, this.version); + break; + case "ss": + this.tryAppendQueryParameter(queries, param, this.services); + break; + case "srt": + this.tryAppendQueryParameter(queries, param, this.resourceTypes); + break; + case "spr": + this.tryAppendQueryParameter(queries, param, this.protocol); + break; + case "st": + this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : void 0); + break; + case "se": + this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : void 0); + break; + case "sip": + this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : void 0); + break; + case "si": + this.tryAppendQueryParameter(queries, param, this.identifier); + break; + case "ses": + this.tryAppendQueryParameter(queries, param, this.encryptionScope); + break; + case "skoid": + this.tryAppendQueryParameter(queries, param, this.signedOid); + break; + case "sktid": + this.tryAppendQueryParameter(queries, param, this.signedTenantId); + break; + case "skt": + this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : void 0); + break; + case "ske": + this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : void 0); + break; + case "sks": + this.tryAppendQueryParameter(queries, param, this.signedService); + break; + case "skv": + this.tryAppendQueryParameter(queries, param, this.signedVersion); + break; + case "sr": + this.tryAppendQueryParameter(queries, param, this.resource); + break; + case "sp": + this.tryAppendQueryParameter(queries, param, this.permissions); + break; + case "sig": + this.tryAppendQueryParameter(queries, param, this.signature); + break; + case "rscc": + this.tryAppendQueryParameter(queries, param, this.cacheControl); + break; + case "rscd": + this.tryAppendQueryParameter(queries, param, this.contentDisposition); + break; + case "rsce": + this.tryAppendQueryParameter(queries, param, this.contentEncoding); + break; + case "rscl": + this.tryAppendQueryParameter(queries, param, this.contentLanguage); + break; + case "rsct": + this.tryAppendQueryParameter(queries, param, this.contentType); + break; + case "saoid": + this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); + break; + case "scid": + this.tryAppendQueryParameter(queries, param, this.correlationId); + break; + } + } + return queries.join("&"); + } + /** + * A private helper method used to filter and append query key/value pairs into an array. + * + * @param queries - + * @param key - + * @param value - + */ + tryAppendQueryParameter(queries, key, value) { + if (!value) { + return; + } + key = encodeURIComponent(key); + value = encodeURIComponent(value); + if (key.length > 0 && value.length > 0) { + queries.push(`${key}=${value}`); + } + } + }; + function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + return generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName).sasQueryParameters; + } + function generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + const version2 = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + const sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey : void 0; + let userDelegationKeyCredential; + if (sharedKeyCredential === void 0 && accountName !== void 0) { + userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); + } + if (sharedKeyCredential === void 0 && userDelegationKeyCredential === void 0) { + throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); + } + if (version2 >= "2020-12-06") { + if (sharedKeyCredential !== void 0) { + return generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKeyCredential); + } else { + return generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userDelegationKeyCredential); + } + } + if (version2 >= "2018-11-09") { + if (sharedKeyCredential !== void 0) { + return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + } else { + if (version2 >= "2020-02-10") { + return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); + } else { + return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); + } + } + } + if (version2 >= "2015-04-05") { + if (sharedKeyCredential !== void 0) { + return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); + } else { + throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); + } + } + throw new RangeError("'version' must be >= '2015-04-05'."); + } + function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + let resource = "c"; + if (blobSASSignatureValues.blobName) { + resource = "b"; + } + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType), + stringToSign + }; + } + function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + let resource = "c"; + let timestamp2 = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp2 = blobSASSignatureValues.versionId; + } + } + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp2, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType), + stringToSign + }; + } + function generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + let resource = "c"; + let timestamp2 = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp2 = blobSASSignatureValues.versionId; + } + } + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp2, + blobSASSignatureValues.encryptionScope, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, void 0, void 0, void 0, blobSASSignatureValues.encryptionScope), + stringToSign + }; + } + function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + let resource = "c"; + let timestamp2 = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp2 = blobSASSignatureValues.versionId; + } + } + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp2, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey), + stringToSign + }; + } + function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + let resource = "c"; + let timestamp2 = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp2 = blobSASSignatureValues.versionId; + } + } + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.preauthorizedAgentObjectId, + void 0, + // agentObjectId + blobSASSignatureValues.correlationId, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp2, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId), + stringToSign + }; + } + function generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userDelegationKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + let resource = "c"; + let timestamp2 = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp2 = blobSASSignatureValues.versionId; + } + } + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", + blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.preauthorizedAgentObjectId, + void 0, + // agentObjectId + blobSASSignatureValues.correlationId, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp2, + blobSASSignatureValues.encryptionScope, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, void 0, void 0, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope), + stringToSign + }; + } + function getCanonicalName(accountName, containerName, blobName) { + const elements = [`/blob/${accountName}/${containerName}`]; + if (blobName) { + elements.push(`/${blobName}`); + } + return elements.join(""); + } + function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { + const version2 = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + if (blobSASSignatureValues.snapshotTime && version2 < "2018-11-09") { + throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === void 0 && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); + } + if (blobSASSignatureValues.versionId && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); + } + if (blobSASSignatureValues.blobName === void 0 && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when providing 'versionId'."); + } + if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.setImmutabilityPolicy && version2 < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); + } + if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.deleteVersion && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); + } + if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.permanentDelete && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when providing 'y' permission."); + } + if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.tag && version2 < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); + } + if (version2 < "2020-02-10" && blobSASSignatureValues.permissions && (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { + throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); + } + if (version2 < "2021-04-10" && blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.filterByTags) { + throw RangeError("'version' must be >= '2021-04-10' when providing the 'f' permission."); + } + if (version2 < "2020-02-10" && (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { + throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); + } + if (blobSASSignatureValues.encryptionScope && version2 < "2020-12-06") { + throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); + } + blobSASSignatureValues.version = version2; + return blobSASSignatureValues; + } + var BlobLeaseClient = class { + /** + * Gets the lease Id. + * + * @readonly + */ + get leaseId() { + return this._leaseId; + } + /** + * Gets the url. + * + * @readonly + */ + get url() { + return this._url; + } + /** + * Creates an instance of BlobLeaseClient. + * @param client - The client to make the lease operation requests. + * @param leaseId - Initial proposed lease id. + */ + constructor(client, leaseId2) { + const clientContext = client.storageClientContext; + this._url = client.url; + if (client.name === void 0) { + this._isContainer = true; + this._containerOrBlobOperation = clientContext.container; + } else { + this._isContainer = false; + this._containerOrBlobOperation = clientContext.blob; + } + if (!leaseId2) { + leaseId2 = coreUtil.randomUUID(); + } + this._leaseId = leaseId2; + } + /** + * Establishes and manages a lock on a container for delete operations, or on a blob + * for write and delete operations. + * The lock duration can be 15 to 60 seconds, or can be infinite. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param duration - Must be between 15 to 60 seconds, or infinite (-1) + * @param options - option to configure lease management operations. + * @returns Response data for acquire lease operation. + */ + async acquireLease(duration2, options = {}) { + var _a, _b, _c, _d, _e; + if (this._isContainer && (((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone || ((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + return tracingClient.withSpan("BlobLeaseClient-acquireLease", options, async (updatedOptions) => { + var _a2; + return assertResponse(await this._containerOrBlobOperation.acquireLease({ + abortSignal: options.abortSignal, + duration: duration2, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a2 = options.conditions) === null || _a2 === void 0 ? void 0 : _a2.tagConditions }), + proposedLeaseId: this._leaseId, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * To change the ID of the lease. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param proposedLeaseId - the proposed new lease Id. + * @param options - option to configure lease management operations. + * @returns Response data for change lease operation. + */ + async changeLease(proposedLeaseId2, options = {}) { + var _a, _b, _c, _d, _e; + if (this._isContainer && (((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone || ((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + return tracingClient.withSpan("BlobLeaseClient-changeLease", options, async (updatedOptions) => { + var _a2; + const response = assertResponse(await this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId2, { + abortSignal: options.abortSignal, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a2 = options.conditions) === null || _a2 === void 0 ? void 0 : _a2.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + })); + this._leaseId = proposedLeaseId2; + return response; + }); + } + /** + * To free the lease if it is no longer needed so that another client may + * immediately acquire a lease against the container or the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param options - option to configure lease management operations. + * @returns Response data for release lease operation. + */ + async releaseLease(options = {}) { + var _a, _b, _c, _d, _e; + if (this._isContainer && (((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone || ((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + return tracingClient.withSpan("BlobLeaseClient-releaseLease", options, async (updatedOptions) => { + var _a2; + return assertResponse(await this._containerOrBlobOperation.releaseLease(this._leaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a2 = options.conditions) === null || _a2 === void 0 ? void 0 : _a2.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * To renew the lease. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param options - Optional option to configure lease management operations. + * @returns Response data for renew lease operation. + */ + async renewLease(options = {}) { + var _a, _b, _c, _d, _e; + if (this._isContainer && (((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone || ((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + return tracingClient.withSpan("BlobLeaseClient-renewLease", options, async (updatedOptions) => { + var _a2; + return this._containerOrBlobOperation.renewLease(this._leaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a2 = options.conditions) === null || _a2 === void 0 ? void 0 : _a2.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + }); + }); + } + /** + * To end the lease but ensure that another client cannot acquire a new lease + * until the current lease period has expired. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param breakPeriod - Break period + * @param options - Optional options to configure lease management operations. + * @returns Response data for break lease operation. + */ + async breakLease(breakPeriod2, options = {}) { + var _a, _b, _c, _d, _e; + if (this._isContainer && (((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone || ((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + return tracingClient.withSpan("BlobLeaseClient-breakLease", options, async (updatedOptions) => { + var _a2; + const operationOptions = { + abortSignal: options.abortSignal, + breakPeriod: breakPeriod2, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a2 = options.conditions) === null || _a2 === void 0 ? void 0 : _a2.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + }; + return assertResponse(await this._containerOrBlobOperation.breakLease(operationOptions)); + }); + } + }; + var RetriableReadableStream = class extends stream.Readable { + /** + * Creates an instance of RetriableReadableStream. + * + * @param source - The current ReadableStream returned from getter + * @param getter - A method calling downloading request returning + * a new ReadableStream from specified offset + * @param offset - Offset position in original data source to read + * @param count - How much data in original data source to read + * @param options - + */ + constructor(source, getter, offset, count, options = {}) { + super({ highWaterMark: options.highWaterMark }); + this.retries = 0; + this.sourceDataHandler = (data) => { + if (this.options.doInjectErrorOnce) { + this.options.doInjectErrorOnce = void 0; + this.source.pause(); + this.sourceErrorOrEndHandler(); + this.source.destroy(); + return; + } + this.offset += data.length; + if (this.onProgress) { + this.onProgress({ loadedBytes: this.offset - this.start }); + } + if (!this.push(data)) { + this.source.pause(); + } + }; + this.sourceAbortedHandler = () => { + const abortError = new abortController.AbortError("The operation was aborted."); + this.destroy(abortError); + }; + this.sourceErrorOrEndHandler = (err) => { + if (err && err.name === "AbortError") { + this.destroy(err); + return; + } + this.removeSourceEventHandlers(); + if (this.offset - 1 === this.end) { + this.push(null); + } else if (this.offset <= this.end) { + if (this.retries < this.maxRetryRequests) { + this.retries += 1; + this.getter(this.offset).then((newSource) => { + this.source = newSource; + this.setSourceEventHandlers(); + return; + }).catch((error2) => { + this.destroy(error2); + }); + } else { + this.destroy(new Error(`Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: ${this.offset - 1}, data needed offset: ${this.end}, retries: ${this.retries}, max retries: ${this.maxRetryRequests}`)); + } + } else { + this.destroy(new Error(`Data corruption failure: Received more data than original request, data needed offset is ${this.end}, received offset: ${this.offset - 1}`)); + } + }; + this.getter = getter; + this.source = source; + this.start = offset; + this.offset = offset; + this.end = offset + count - 1; + this.maxRetryRequests = options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; + this.onProgress = options.onProgress; + this.options = options; + this.setSourceEventHandlers(); + } + _read() { + this.source.resume(); + } + setSourceEventHandlers() { + this.source.on("data", this.sourceDataHandler); + this.source.on("end", this.sourceErrorOrEndHandler); + this.source.on("error", this.sourceErrorOrEndHandler); + this.source.on("aborted", this.sourceAbortedHandler); + } + removeSourceEventHandlers() { + this.source.removeListener("data", this.sourceDataHandler); + this.source.removeListener("end", this.sourceErrorOrEndHandler); + this.source.removeListener("error", this.sourceErrorOrEndHandler); + this.source.removeListener("aborted", this.sourceAbortedHandler); + } + _destroy(error2, callback) { + this.removeSourceEventHandlers(); + this.source.destroy(); + callback(error2 === null ? void 0 : error2); + } + }; + var BlobDownloadResponse = class { + /** + * Indicates that the service supports + * requests for partial file content. + * + * @readonly + */ + get acceptRanges() { + return this.originalResponse.acceptRanges; + } + /** + * Returns if it was previously specified + * for the file. + * + * @readonly + */ + get cacheControl() { + return this.originalResponse.cacheControl; + } + /** + * Returns the value that was specified + * for the 'x-ms-content-disposition' header and specifies how to process the + * response. + * + * @readonly + */ + get contentDisposition() { + return this.originalResponse.contentDisposition; + } + /** + * Returns the value that was specified + * for the Content-Encoding request header. + * + * @readonly + */ + get contentEncoding() { + return this.originalResponse.contentEncoding; + } + /** + * Returns the value that was specified + * for the Content-Language request header. + * + * @readonly + */ + get contentLanguage() { + return this.originalResponse.contentLanguage; + } + /** + * The current sequence number for a + * page blob. This header is not returned for block blobs or append blobs. + * + * @readonly + */ + get blobSequenceNumber() { + return this.originalResponse.blobSequenceNumber; + } + /** + * The blob's type. Possible values include: + * 'BlockBlob', 'PageBlob', 'AppendBlob'. + * + * @readonly + */ + get blobType() { + return this.originalResponse.blobType; + } + /** + * The number of bytes present in the + * response body. + * + * @readonly + */ + get contentLength() { + return this.originalResponse.contentLength; + } + /** + * If the file has an MD5 hash and the + * request is to read the full file, this response header is returned so that + * the client can check for message content integrity. If the request is to + * read a specified range and the 'x-ms-range-get-content-md5' is set to + * true, then the request returns an MD5 hash for the range, as long as the + * range size is less than or equal to 4 MB. If neither of these sets of + * conditions is true, then no value is returned for the 'Content-MD5' + * header. + * + * @readonly + */ + get contentMD5() { + return this.originalResponse.contentMD5; + } + /** + * Indicates the range of bytes returned if + * the client requested a subset of the file by setting the Range request + * header. + * + * @readonly + */ + get contentRange() { + return this.originalResponse.contentRange; + } + /** + * The content type specified for the file. + * The default content type is 'application/octet-stream' + * + * @readonly + */ + get contentType() { + return this.originalResponse.contentType; + } + /** + * Conclusion time of the last attempted + * Copy File operation where this file was the destination file. This value + * can specify the time of a completed, aborted, or failed copy attempt. + * + * @readonly + */ + get copyCompletedOn() { + return this.originalResponse.copyCompletedOn; + } + /** + * String identifier for the last attempted Copy + * File operation where this file was the destination file. + * + * @readonly + */ + get copyId() { + return this.originalResponse.copyId; + } + /** + * Contains the number of bytes copied and + * the total bytes in the source in the last attempted Copy File operation + * where this file was the destination file. Can show between 0 and + * Content-Length bytes copied. + * + * @readonly + */ + get copyProgress() { + return this.originalResponse.copyProgress; + } + /** + * URL up to 2KB in length that specifies the + * source file used in the last attempted Copy File operation where this file + * was the destination file. + * + * @readonly + */ + get copySource() { + return this.originalResponse.copySource; + } + /** + * State of the copy operation + * identified by 'x-ms-copy-id'. Possible values include: 'pending', + * 'success', 'aborted', 'failed' + * + * @readonly + */ + get copyStatus() { + return this.originalResponse.copyStatus; + } + /** + * Only appears when + * x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * + * @readonly + */ + get copyStatusDescription() { + return this.originalResponse.copyStatusDescription; + } + /** + * When a blob is leased, + * specifies whether the lease is of infinite or fixed duration. Possible + * values include: 'infinite', 'fixed'. + * + * @readonly + */ + get leaseDuration() { + return this.originalResponse.leaseDuration; + } + /** + * Lease state of the blob. Possible + * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. + * + * @readonly + */ + get leaseState() { + return this.originalResponse.leaseState; + } + /** + * The current lease status of the + * blob. Possible values include: 'locked', 'unlocked'. + * + * @readonly + */ + get leaseStatus() { + return this.originalResponse.leaseStatus; + } + /** + * A UTC date/time value generated by the service that + * indicates the time at which the response was initiated. + * + * @readonly + */ + get date() { + return this.originalResponse.date; + } + /** + * The number of committed blocks + * present in the blob. This header is returned only for append blobs. + * + * @readonly + */ + get blobCommittedBlockCount() { + return this.originalResponse.blobCommittedBlockCount; + } + /** + * The ETag contains a value that you can use to + * perform operations conditionally, in quotes. + * + * @readonly + */ + get etag() { + return this.originalResponse.etag; + } + /** + * The number of tags associated with the blob + * + * @readonly + */ + get tagCount() { + return this.originalResponse.tagCount; + } + /** + * The error code. + * + * @readonly + */ + get errorCode() { + return this.originalResponse.errorCode; + } + /** + * The value of this header is set to + * true if the file data and application metadata are completely encrypted + * using the specified algorithm. Otherwise, the value is set to false (when + * the file is unencrypted, or if only parts of the file/application metadata + * are encrypted). + * + * @readonly + */ + get isServerEncrypted() { + return this.originalResponse.isServerEncrypted; + } + /** + * If the blob has a MD5 hash, and if + * request contains range header (Range or x-ms-range), this response header + * is returned with the value of the whole blob's MD5 value. This value may + * or may not be equal to the value returned in Content-MD5 header, with the + * latter calculated from the requested range. + * + * @readonly + */ + get blobContentMD5() { + return this.originalResponse.blobContentMD5; + } + /** + * Returns the date and time the file was last + * modified. Any operation that modifies the file or its properties updates + * the last modified time. + * + * @readonly + */ + get lastModified() { + return this.originalResponse.lastModified; + } + /** + * Returns the UTC date and time generated by the service that indicates the time at which the blob was + * last read or written to. + * + * @readonly + */ + get lastAccessed() { + return this.originalResponse.lastAccessed; + } + /** + * Returns the date and time the blob was created. + * + * @readonly + */ + get createdOn() { + return this.originalResponse.createdOn; + } + /** + * A name-value pair + * to associate with a file storage object. + * + * @readonly + */ + get metadata() { + return this.originalResponse.metadata; + } + /** + * This header uniquely identifies the request + * that was made and can be used for troubleshooting the request. + * + * @readonly + */ + get requestId() { + return this.originalResponse.requestId; + } + /** + * If a client request id header is sent in the request, this header will be present in the + * response with the same value. + * + * @readonly + */ + get clientRequestId() { + return this.originalResponse.clientRequestId; + } + /** + * Indicates the version of the Blob service used + * to execute the request. + * + * @readonly + */ + get version() { + return this.originalResponse.version; + } + /** + * Indicates the versionId of the downloaded blob version. + * + * @readonly + */ + get versionId() { + return this.originalResponse.versionId; + } + /** + * Indicates whether version of this blob is a current version. + * + * @readonly + */ + get isCurrentVersion() { + return this.originalResponse.isCurrentVersion; + } + /** + * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned + * when the blob was encrypted with a customer-provided key. + * + * @readonly + */ + get encryptionKeySha256() { + return this.originalResponse.encryptionKeySha256; + } + /** + * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to + * true, then the request returns a crc64 for the range, as long as the range size is less than + * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is + * specified in the same request, it will fail with 400(Bad Request) + */ + get contentCrc64() { + return this.originalResponse.contentCrc64; + } + /** + * Object Replication Policy Id of the destination blob. + * + * @readonly + */ + get objectReplicationDestinationPolicyId() { + return this.originalResponse.objectReplicationDestinationPolicyId; + } + /** + * Parsed Object Replication Policy Id, Rule Id(s) and status of the source blob. + * + * @readonly + */ + get objectReplicationSourceProperties() { + return this.originalResponse.objectReplicationSourceProperties; + } + /** + * If this blob has been sealed. + * + * @readonly + */ + get isSealed() { + return this.originalResponse.isSealed; + } + /** + * UTC date/time value generated by the service that indicates the time at which the blob immutability policy will expire. + * + * @readonly + */ + get immutabilityPolicyExpiresOn() { + return this.originalResponse.immutabilityPolicyExpiresOn; + } + /** + * Indicates immutability policy mode. + * + * @readonly + */ + get immutabilityPolicyMode() { + return this.originalResponse.immutabilityPolicyMode; + } + /** + * Indicates if a legal hold is present on the blob. + * + * @readonly + */ + get legalHold() { + return this.originalResponse.legalHold; + } + /** + * The response body as a browser Blob. + * Always undefined in node.js. + * + * @readonly + */ + get contentAsBlob() { + return this.originalResponse.blobBody; + } + /** + * The response body as a node.js Readable stream. + * Always undefined in the browser. + * + * It will automatically retry when internal read stream unexpected ends. + * + * @readonly + */ + get readableStreamBody() { + return coreUtil.isNode ? this.blobDownloadStream : void 0; + } + /** + * The HTTP response. + */ + get _response() { + return this.originalResponse._response; + } + /** + * Creates an instance of BlobDownloadResponse. + * + * @param originalResponse - + * @param getter - + * @param offset - + * @param count - + * @param options - + */ + constructor(originalResponse, getter, offset, count, options = {}) { + this.originalResponse = originalResponse; + this.blobDownloadStream = new RetriableReadableStream(this.originalResponse.readableStreamBody, getter, offset, count, options); + } + }; + var AVRO_SYNC_MARKER_SIZE = 16; + var AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); + var AVRO_CODEC_KEY = "avro.codec"; + var AVRO_SCHEMA_KEY = "avro.schema"; + var AvroParser = class _AvroParser { + /** + * Reads a fixed number of bytes from the stream. + * + * @param stream - + * @param length - + * @param options - + */ + static async readFixedBytes(stream2, length, options = {}) { + const bytes = await stream2.read(length, { abortSignal: options.abortSignal }); + if (bytes.length !== length) { + throw new Error("Hit stream end."); + } + return bytes; + } + /** + * Reads a single byte from the stream. + * + * @param stream - + * @param options - + */ + static async readByte(stream2, options = {}) { + const buf = await _AvroParser.readFixedBytes(stream2, 1, options); + return buf[0]; + } + // int and long are stored in variable-length zig-zag coding. + // variable-length: https://lucene.apache.org/core/3_5_0/fileformats.html#VInt + // zig-zag: https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types + static async readZigZagLong(stream2, options = {}) { + let zigZagEncoded = 0; + let significanceInBit = 0; + let byte, haveMoreByte, significanceInFloat; + do { + byte = await _AvroParser.readByte(stream2, options); + haveMoreByte = byte & 128; + zigZagEncoded |= (byte & 127) << significanceInBit; + significanceInBit += 7; + } while (haveMoreByte && significanceInBit < 28); + if (haveMoreByte) { + zigZagEncoded = zigZagEncoded; + significanceInFloat = 268435456; + do { + byte = await _AvroParser.readByte(stream2, options); + zigZagEncoded += (byte & 127) * significanceInFloat; + significanceInFloat *= 128; + } while (byte & 128); + const res = (zigZagEncoded % 2 ? -(zigZagEncoded + 1) : zigZagEncoded) / 2; + if (res < Number.MIN_SAFE_INTEGER || res > Number.MAX_SAFE_INTEGER) { + throw new Error("Integer overflow."); + } + return res; + } + return zigZagEncoded >> 1 ^ -(zigZagEncoded & 1); + } + static async readLong(stream2, options = {}) { + return _AvroParser.readZigZagLong(stream2, options); + } + static async readInt(stream2, options = {}) { + return _AvroParser.readZigZagLong(stream2, options); + } + static async readNull() { + return null; + } + static async readBoolean(stream2, options = {}) { + const b = await _AvroParser.readByte(stream2, options); + if (b === 1) { + return true; + } else if (b === 0) { + return false; + } else { + throw new Error("Byte was not a boolean."); + } + } + static async readFloat(stream2, options = {}) { + const u8arr = await _AvroParser.readFixedBytes(stream2, 4, options); + const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); + return view.getFloat32(0, true); + } + static async readDouble(stream2, options = {}) { + const u8arr = await _AvroParser.readFixedBytes(stream2, 8, options); + const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); + return view.getFloat64(0, true); + } + static async readBytes(stream2, options = {}) { + const size = await _AvroParser.readLong(stream2, options); + if (size < 0) { + throw new Error("Bytes size was negative."); + } + return stream2.read(size, { abortSignal: options.abortSignal }); + } + static async readString(stream2, options = {}) { + const u8arr = await _AvroParser.readBytes(stream2, options); + const utf8decoder = new TextDecoder(); + return utf8decoder.decode(u8arr); + } + static async readMapPair(stream2, readItemMethod, options = {}) { + const key = await _AvroParser.readString(stream2, options); + const value = await readItemMethod(stream2, options); + return { key, value }; + } + static async readMap(stream2, readItemMethod, options = {}) { + const readPairMethod = (s, opts = {}) => { + return _AvroParser.readMapPair(s, readItemMethod, opts); + }; + const pairs2 = await _AvroParser.readArray(stream2, readPairMethod, options); + const dict = {}; + for (const pair of pairs2) { + dict[pair.key] = pair.value; + } + return dict; + } + static async readArray(stream2, readItemMethod, options = {}) { + const items = []; + for (let count = await _AvroParser.readLong(stream2, options); count !== 0; count = await _AvroParser.readLong(stream2, options)) { + if (count < 0) { + await _AvroParser.readLong(stream2, options); + count = -count; + } + while (count--) { + const item = await readItemMethod(stream2, options); + items.push(item); + } + } + return items; + } + }; + var AvroComplex; + (function(AvroComplex2) { + AvroComplex2["RECORD"] = "record"; + AvroComplex2["ENUM"] = "enum"; + AvroComplex2["ARRAY"] = "array"; + AvroComplex2["MAP"] = "map"; + AvroComplex2["UNION"] = "union"; + AvroComplex2["FIXED"] = "fixed"; + })(AvroComplex || (AvroComplex = {})); + var AvroPrimitive; + (function(AvroPrimitive2) { + AvroPrimitive2["NULL"] = "null"; + AvroPrimitive2["BOOLEAN"] = "boolean"; + AvroPrimitive2["INT"] = "int"; + AvroPrimitive2["LONG"] = "long"; + AvroPrimitive2["FLOAT"] = "float"; + AvroPrimitive2["DOUBLE"] = "double"; + AvroPrimitive2["BYTES"] = "bytes"; + AvroPrimitive2["STRING"] = "string"; + })(AvroPrimitive || (AvroPrimitive = {})); + var AvroType = class _AvroType { + /** + * Determines the AvroType from the Avro Schema. + */ + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types + static fromSchema(schema2) { + if (typeof schema2 === "string") { + return _AvroType.fromStringSchema(schema2); + } else if (Array.isArray(schema2)) { + return _AvroType.fromArraySchema(schema2); + } else { + return _AvroType.fromObjectSchema(schema2); + } + } + static fromStringSchema(schema2) { + switch (schema2) { + case AvroPrimitive.NULL: + case AvroPrimitive.BOOLEAN: + case AvroPrimitive.INT: + case AvroPrimitive.LONG: + case AvroPrimitive.FLOAT: + case AvroPrimitive.DOUBLE: + case AvroPrimitive.BYTES: + case AvroPrimitive.STRING: + return new AvroPrimitiveType(schema2); + default: + throw new Error(`Unexpected Avro type ${schema2}`); + } + } + static fromArraySchema(schema2) { + return new AvroUnionType(schema2.map(_AvroType.fromSchema)); + } + static fromObjectSchema(schema2) { + const type2 = schema2.type; + try { + return _AvroType.fromStringSchema(type2); + } catch (_a) { + } + switch (type2) { + case AvroComplex.RECORD: + if (schema2.aliases) { + throw new Error(`aliases currently is not supported, schema: ${schema2}`); + } + if (!schema2.name) { + throw new Error(`Required attribute 'name' doesn't exist on schema: ${schema2}`); + } + const fields = {}; + if (!schema2.fields) { + throw new Error(`Required attribute 'fields' doesn't exist on schema: ${schema2}`); + } + for (const field of schema2.fields) { + fields[field.name] = _AvroType.fromSchema(field.type); + } + return new AvroRecordType(fields, schema2.name); + case AvroComplex.ENUM: + if (schema2.aliases) { + throw new Error(`aliases currently is not supported, schema: ${schema2}`); + } + if (!schema2.symbols) { + throw new Error(`Required attribute 'symbols' doesn't exist on schema: ${schema2}`); + } + return new AvroEnumType(schema2.symbols); + case AvroComplex.MAP: + if (!schema2.values) { + throw new Error(`Required attribute 'values' doesn't exist on schema: ${schema2}`); + } + return new AvroMapType(_AvroType.fromSchema(schema2.values)); + case AvroComplex.ARRAY: + // Unused today + case AvroComplex.FIXED: + // Unused today + default: + throw new Error(`Unexpected Avro type ${type2} in ${schema2}`); + } + } + }; + var AvroPrimitiveType = class extends AvroType { + constructor(primitive) { + super(); + this._primitive = primitive; + } + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types + read(stream2, options = {}) { + switch (this._primitive) { + case AvroPrimitive.NULL: + return AvroParser.readNull(); + case AvroPrimitive.BOOLEAN: + return AvroParser.readBoolean(stream2, options); + case AvroPrimitive.INT: + return AvroParser.readInt(stream2, options); + case AvroPrimitive.LONG: + return AvroParser.readLong(stream2, options); + case AvroPrimitive.FLOAT: + return AvroParser.readFloat(stream2, options); + case AvroPrimitive.DOUBLE: + return AvroParser.readDouble(stream2, options); + case AvroPrimitive.BYTES: + return AvroParser.readBytes(stream2, options); + case AvroPrimitive.STRING: + return AvroParser.readString(stream2, options); + default: + throw new Error("Unknown Avro Primitive"); + } + } + }; + var AvroEnumType = class extends AvroType { + constructor(symbols) { + super(); + this._symbols = symbols; + } + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types + async read(stream2, options = {}) { + const value = await AvroParser.readInt(stream2, options); + return this._symbols[value]; + } + }; + var AvroUnionType = class extends AvroType { + constructor(types) { + super(); + this._types = types; + } + async read(stream2, options = {}) { + const typeIndex = await AvroParser.readInt(stream2, options); + return this._types[typeIndex].read(stream2, options); + } + }; + var AvroMapType = class extends AvroType { + constructor(itemType) { + super(); + this._itemType = itemType; + } + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types + read(stream2, options = {}) { + const readItemMethod = (s, opts) => { + return this._itemType.read(s, opts); + }; + return AvroParser.readMap(stream2, readItemMethod, options); + } + }; + var AvroRecordType = class extends AvroType { + constructor(fields, name) { + super(); + this._fields = fields; + this._name = name; + } + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types + async read(stream2, options = {}) { + const record = {}; + record["$schema"] = this._name; + for (const key in this._fields) { + if (Object.prototype.hasOwnProperty.call(this._fields, key)) { + record[key] = await this._fields[key].read(stream2, options); + } + } + return record; + } + }; + function arraysEqual(a, b) { + if (a === b) + return true; + if (a == null || b == null) + return false; + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) + return false; + } + return true; + } + var AvroReader = class { + get blockOffset() { + return this._blockOffset; + } + get objectIndex() { + return this._objectIndex; + } + constructor(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { + this._dataStream = dataStream; + this._headerStream = headerStream || dataStream; + this._initialized = false; + this._blockOffset = currentBlockOffset || 0; + this._objectIndex = indexWithinCurrentBlock || 0; + this._initialBlockOffset = currentBlockOffset || 0; + } + async initialize(options = {}) { + const header = await AvroParser.readFixedBytes(this._headerStream, AVRO_INIT_BYTES.length, { + abortSignal: options.abortSignal + }); + if (!arraysEqual(header, AVRO_INIT_BYTES)) { + throw new Error("Stream is not an Avro file."); + } + this._metadata = await AvroParser.readMap(this._headerStream, AvroParser.readString, { + abortSignal: options.abortSignal + }); + const codec = this._metadata[AVRO_CODEC_KEY]; + if (!(codec === void 0 || codec === null || codec === "null")) { + throw new Error("Codecs are not supported"); + } + this._syncMarker = await AvroParser.readFixedBytes(this._headerStream, AVRO_SYNC_MARKER_SIZE, { + abortSignal: options.abortSignal + }); + const schema2 = JSON.parse(this._metadata[AVRO_SCHEMA_KEY]); + this._itemType = AvroType.fromSchema(schema2); + if (this._blockOffset === 0) { + this._blockOffset = this._initialBlockOffset + this._dataStream.position; + } + this._itemsRemainingInBlock = await AvroParser.readLong(this._dataStream, { + abortSignal: options.abortSignal + }); + await AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); + this._initialized = true; + if (this._objectIndex && this._objectIndex > 0) { + for (let i = 0; i < this._objectIndex; i++) { + await this._itemType.read(this._dataStream, { abortSignal: options.abortSignal }); + this._itemsRemainingInBlock--; + } + } + } + hasNext() { + return !this._initialized || this._itemsRemainingInBlock > 0; + } + parseObjects() { + return tslib.__asyncGenerator(this, arguments, function* parseObjects_1(options = {}) { + if (!this._initialized) { + yield tslib.__await(this.initialize(options)); + } + while (this.hasNext()) { + const result = yield tslib.__await(this._itemType.read(this._dataStream, { + abortSignal: options.abortSignal + })); + this._itemsRemainingInBlock--; + this._objectIndex++; + if (this._itemsRemainingInBlock === 0) { + const marker2 = yield tslib.__await(AvroParser.readFixedBytes(this._dataStream, AVRO_SYNC_MARKER_SIZE, { + abortSignal: options.abortSignal + })); + this._blockOffset = this._initialBlockOffset + this._dataStream.position; + this._objectIndex = 0; + if (!arraysEqual(this._syncMarker, marker2)) { + throw new Error("Stream is not a valid Avro file."); + } + try { + this._itemsRemainingInBlock = yield tslib.__await(AvroParser.readLong(this._dataStream, { + abortSignal: options.abortSignal + })); + } catch (_a) { + this._itemsRemainingInBlock = 0; + } + if (this._itemsRemainingInBlock > 0) { + yield tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal })); + } + } + yield yield tslib.__await(result); + } + }); + } + }; + var AvroReadable = class { + }; + var ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); + var AvroReadableFromStream = class extends AvroReadable { + toUint8Array(data) { + if (typeof data === "string") { + return Buffer.from(data); + } + return data; + } + constructor(readable) { + super(); + this._readable = readable; + this._position = 0; + } + get position() { + return this._position; + } + async read(size, options = {}) { + var _a; + if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + throw ABORT_ERROR; + } + if (size < 0) { + throw new Error(`size parameter should be positive: ${size}`); + } + if (size === 0) { + return new Uint8Array(); + } + if (!this._readable.readable) { + throw new Error("Stream no longer readable."); + } + const chunk = this._readable.read(size); + if (chunk) { + this._position += chunk.length; + return this.toUint8Array(chunk); + } else { + return new Promise((resolve2, reject) => { + const cleanUp = () => { + this._readable.removeListener("readable", readableCallback); + this._readable.removeListener("error", rejectCallback); + this._readable.removeListener("end", rejectCallback); + this._readable.removeListener("close", rejectCallback); + if (options.abortSignal) { + options.abortSignal.removeEventListener("abort", abortHandler); + } + }; + const readableCallback = () => { + const callbackChunk = this._readable.read(size); + if (callbackChunk) { + this._position += callbackChunk.length; + cleanUp(); + resolve2(this.toUint8Array(callbackChunk)); + } + }; + const rejectCallback = () => { + cleanUp(); + reject(); + }; + const abortHandler = () => { + cleanUp(); + reject(ABORT_ERROR); + }; + this._readable.on("readable", readableCallback); + this._readable.once("error", rejectCallback); + this._readable.once("end", rejectCallback); + this._readable.once("close", rejectCallback); + if (options.abortSignal) { + options.abortSignal.addEventListener("abort", abortHandler); + } + }); + } + } + }; + var BlobQuickQueryStream = class extends stream.Readable { + /** + * Creates an instance of BlobQuickQueryStream. + * + * @param source - The current ReadableStream returned from getter + * @param options - + */ + constructor(source, options = {}) { + super(); + this.avroPaused = true; + this.source = source; + this.onProgress = options.onProgress; + this.onError = options.onError; + this.avroReader = new AvroReader(new AvroReadableFromStream(this.source)); + this.avroIter = this.avroReader.parseObjects({ abortSignal: options.abortSignal }); + } + _read() { + if (this.avroPaused) { + this.readInternal().catch((err) => { + this.emit("error", err); + }); + } + } + async readInternal() { + this.avroPaused = false; + let avroNext; + do { + avroNext = await this.avroIter.next(); + if (avroNext.done) { + break; + } + const obj = avroNext.value; + const schema2 = obj.$schema; + if (typeof schema2 !== "string") { + throw Error("Missing schema in avro record."); + } + switch (schema2) { + case "com.microsoft.azure.storage.queryBlobContents.resultData": + { + const data = obj.data; + if (data instanceof Uint8Array === false) { + throw Error("Invalid data in avro result record."); + } + if (!this.push(Buffer.from(data))) { + this.avroPaused = true; + } + } + break; + case "com.microsoft.azure.storage.queryBlobContents.progress": + { + const bytesScanned = obj.bytesScanned; + if (typeof bytesScanned !== "number") { + throw Error("Invalid bytesScanned in avro progress record."); + } + if (this.onProgress) { + this.onProgress({ loadedBytes: bytesScanned }); + } + } + break; + case "com.microsoft.azure.storage.queryBlobContents.end": + if (this.onProgress) { + const totalBytes = obj.totalBytes; + if (typeof totalBytes !== "number") { + throw Error("Invalid totalBytes in avro end record."); + } + this.onProgress({ loadedBytes: totalBytes }); + } + this.push(null); + break; + case "com.microsoft.azure.storage.queryBlobContents.error": + if (this.onError) { + const fatal = obj.fatal; + if (typeof fatal !== "boolean") { + throw Error("Invalid fatal in avro error record."); + } + const name = obj.name; + if (typeof name !== "string") { + throw Error("Invalid name in avro error record."); + } + const description = obj.description; + if (typeof description !== "string") { + throw Error("Invalid description in avro error record."); + } + const position = obj.position; + if (typeof position !== "number") { + throw Error("Invalid position in avro error record."); + } + this.onError({ + position, + name, + isFatal: fatal, + description + }); + } + break; + default: + throw Error(`Unknown schema ${schema2} in avro progress record.`); + } + } while (!avroNext.done && !this.avroPaused); + } + }; + var BlobQueryResponse = class { + /** + * Indicates that the service supports + * requests for partial file content. + * + * @readonly + */ + get acceptRanges() { + return this.originalResponse.acceptRanges; + } + /** + * Returns if it was previously specified + * for the file. + * + * @readonly + */ + get cacheControl() { + return this.originalResponse.cacheControl; + } + /** + * Returns the value that was specified + * for the 'x-ms-content-disposition' header and specifies how to process the + * response. + * + * @readonly + */ + get contentDisposition() { + return this.originalResponse.contentDisposition; + } + /** + * Returns the value that was specified + * for the Content-Encoding request header. + * + * @readonly + */ + get contentEncoding() { + return this.originalResponse.contentEncoding; + } + /** + * Returns the value that was specified + * for the Content-Language request header. + * + * @readonly + */ + get contentLanguage() { + return this.originalResponse.contentLanguage; + } + /** + * The current sequence number for a + * page blob. This header is not returned for block blobs or append blobs. + * + * @readonly + */ + get blobSequenceNumber() { + return this.originalResponse.blobSequenceNumber; + } + /** + * The blob's type. Possible values include: + * 'BlockBlob', 'PageBlob', 'AppendBlob'. + * + * @readonly + */ + get blobType() { + return this.originalResponse.blobType; + } + /** + * The number of bytes present in the + * response body. + * + * @readonly + */ + get contentLength() { + return this.originalResponse.contentLength; + } + /** + * If the file has an MD5 hash and the + * request is to read the full file, this response header is returned so that + * the client can check for message content integrity. If the request is to + * read a specified range and the 'x-ms-range-get-content-md5' is set to + * true, then the request returns an MD5 hash for the range, as long as the + * range size is less than or equal to 4 MB. If neither of these sets of + * conditions is true, then no value is returned for the 'Content-MD5' + * header. + * + * @readonly + */ + get contentMD5() { + return this.originalResponse.contentMD5; + } + /** + * Indicates the range of bytes returned if + * the client requested a subset of the file by setting the Range request + * header. + * + * @readonly + */ + get contentRange() { + return this.originalResponse.contentRange; + } + /** + * The content type specified for the file. + * The default content type is 'application/octet-stream' + * + * @readonly + */ + get contentType() { + return this.originalResponse.contentType; + } + /** + * Conclusion time of the last attempted + * Copy File operation where this file was the destination file. This value + * can specify the time of a completed, aborted, or failed copy attempt. + * + * @readonly + */ + get copyCompletedOn() { + return void 0; + } + /** + * String identifier for the last attempted Copy + * File operation where this file was the destination file. + * + * @readonly + */ + get copyId() { + return this.originalResponse.copyId; + } + /** + * Contains the number of bytes copied and + * the total bytes in the source in the last attempted Copy File operation + * where this file was the destination file. Can show between 0 and + * Content-Length bytes copied. + * + * @readonly + */ + get copyProgress() { + return this.originalResponse.copyProgress; + } + /** + * URL up to 2KB in length that specifies the + * source file used in the last attempted Copy File operation where this file + * was the destination file. + * + * @readonly + */ + get copySource() { + return this.originalResponse.copySource; + } + /** + * State of the copy operation + * identified by 'x-ms-copy-id'. Possible values include: 'pending', + * 'success', 'aborted', 'failed' + * + * @readonly + */ + get copyStatus() { + return this.originalResponse.copyStatus; + } + /** + * Only appears when + * x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * + * @readonly + */ + get copyStatusDescription() { + return this.originalResponse.copyStatusDescription; + } + /** + * When a blob is leased, + * specifies whether the lease is of infinite or fixed duration. Possible + * values include: 'infinite', 'fixed'. + * + * @readonly + */ + get leaseDuration() { + return this.originalResponse.leaseDuration; + } + /** + * Lease state of the blob. Possible + * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. + * + * @readonly + */ + get leaseState() { + return this.originalResponse.leaseState; + } + /** + * The current lease status of the + * blob. Possible values include: 'locked', 'unlocked'. + * + * @readonly + */ + get leaseStatus() { + return this.originalResponse.leaseStatus; + } + /** + * A UTC date/time value generated by the service that + * indicates the time at which the response was initiated. + * + * @readonly + */ + get date() { + return this.originalResponse.date; + } + /** + * The number of committed blocks + * present in the blob. This header is returned only for append blobs. + * + * @readonly + */ + get blobCommittedBlockCount() { + return this.originalResponse.blobCommittedBlockCount; + } + /** + * The ETag contains a value that you can use to + * perform operations conditionally, in quotes. + * + * @readonly + */ + get etag() { + return this.originalResponse.etag; + } + /** + * The error code. + * + * @readonly + */ + get errorCode() { + return this.originalResponse.errorCode; + } + /** + * The value of this header is set to + * true if the file data and application metadata are completely encrypted + * using the specified algorithm. Otherwise, the value is set to false (when + * the file is unencrypted, or if only parts of the file/application metadata + * are encrypted). + * + * @readonly + */ + get isServerEncrypted() { + return this.originalResponse.isServerEncrypted; + } + /** + * If the blob has a MD5 hash, and if + * request contains range header (Range or x-ms-range), this response header + * is returned with the value of the whole blob's MD5 value. This value may + * or may not be equal to the value returned in Content-MD5 header, with the + * latter calculated from the requested range. + * + * @readonly + */ + get blobContentMD5() { + return this.originalResponse.blobContentMD5; + } + /** + * Returns the date and time the file was last + * modified. Any operation that modifies the file or its properties updates + * the last modified time. + * + * @readonly + */ + get lastModified() { + return this.originalResponse.lastModified; + } + /** + * A name-value pair + * to associate with a file storage object. + * + * @readonly + */ + get metadata() { + return this.originalResponse.metadata; + } + /** + * This header uniquely identifies the request + * that was made and can be used for troubleshooting the request. + * + * @readonly + */ + get requestId() { + return this.originalResponse.requestId; + } + /** + * If a client request id header is sent in the request, this header will be present in the + * response with the same value. + * + * @readonly + */ + get clientRequestId() { + return this.originalResponse.clientRequestId; + } + /** + * Indicates the version of the File service used + * to execute the request. + * + * @readonly + */ + get version() { + return this.originalResponse.version; + } + /** + * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned + * when the blob was encrypted with a customer-provided key. + * + * @readonly + */ + get encryptionKeySha256() { + return this.originalResponse.encryptionKeySha256; + } + /** + * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to + * true, then the request returns a crc64 for the range, as long as the range size is less than + * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is + * specified in the same request, it will fail with 400(Bad Request) + */ + get contentCrc64() { + return this.originalResponse.contentCrc64; + } + /** + * The response body as a browser Blob. + * Always undefined in node.js. + * + * @readonly + */ + get blobBody() { + return void 0; + } + /** + * The response body as a node.js Readable stream. + * Always undefined in the browser. + * + * It will parse avor data returned by blob query. + * + * @readonly + */ + get readableStreamBody() { + return coreUtil.isNode ? this.blobDownloadStream : void 0; + } + /** + * The HTTP response. + */ + get _response() { + return this.originalResponse._response; + } + /** + * Creates an instance of BlobQueryResponse. + * + * @param originalResponse - + * @param options - + */ + constructor(originalResponse, options = {}) { + this.originalResponse = originalResponse; + this.blobDownloadStream = new BlobQuickQueryStream(this.originalResponse.readableStreamBody, options); + } + }; + exports2.BlockBlobTier = void 0; + (function(BlockBlobTier) { + BlockBlobTier["Hot"] = "Hot"; + BlockBlobTier["Cool"] = "Cool"; + BlockBlobTier["Cold"] = "Cold"; + BlockBlobTier["Archive"] = "Archive"; + })(exports2.BlockBlobTier || (exports2.BlockBlobTier = {})); + exports2.PremiumPageBlobTier = void 0; + (function(PremiumPageBlobTier) { + PremiumPageBlobTier["P4"] = "P4"; + PremiumPageBlobTier["P6"] = "P6"; + PremiumPageBlobTier["P10"] = "P10"; + PremiumPageBlobTier["P15"] = "P15"; + PremiumPageBlobTier["P20"] = "P20"; + PremiumPageBlobTier["P30"] = "P30"; + PremiumPageBlobTier["P40"] = "P40"; + PremiumPageBlobTier["P50"] = "P50"; + PremiumPageBlobTier["P60"] = "P60"; + PremiumPageBlobTier["P70"] = "P70"; + PremiumPageBlobTier["P80"] = "P80"; + })(exports2.PremiumPageBlobTier || (exports2.PremiumPageBlobTier = {})); + function toAccessTier(tier2) { + if (tier2 === void 0) { + return void 0; + } + return tier2; + } + function ensureCpkIfSpecified(cpk, isHttps) { + if (cpk && !isHttps) { + throw new RangeError("Customer-provided encryption key must be used over HTTPS."); + } + if (cpk && !cpk.encryptionAlgorithm) { + cpk.encryptionAlgorithm = EncryptionAlgorithmAES25; + } + } + exports2.StorageBlobAudience = void 0; + (function(StorageBlobAudience) { + StorageBlobAudience["StorageOAuthScopes"] = "https://storage.azure.com/.default"; + StorageBlobAudience["DiskComputeOAuthScopes"] = "https://disk.compute.azure.com/.default"; + })(exports2.StorageBlobAudience || (exports2.StorageBlobAudience = {})); + function getBlobServiceAccountAudience(storageAccountName) { + return `https://${storageAccountName}.blob.core.windows.net/.default`; + } + function rangeResponseFromModel(response) { + const pageRange = (response._response.parsedBody.pageRange || []).map((x) => ({ + offset: x.start, + count: x.end - x.start + })); + const clearRange = (response._response.parsedBody.clearRange || []).map((x) => ({ + offset: x.start, + count: x.end - x.start + })); + return Object.assign(Object.assign({}, response), { + pageRange, + clearRange, + _response: Object.assign(Object.assign({}, response._response), { parsedBody: { + pageRange, + clearRange + } }) + }); + } + var BlobBeginCopyFromUrlPoller = class extends coreLro.Poller { + constructor(options) { + const { blobClient, copySource: copySource2, intervalInMs = 15e3, onProgress, resumeFrom, startCopyFromURLOptions } = options; + let state; + if (resumeFrom) { + state = JSON.parse(resumeFrom).state; + } + const operation = makeBlobBeginCopyFromURLPollOperation(Object.assign(Object.assign({}, state), { + blobClient, + copySource: copySource2, + startCopyFromURLOptions + })); + super(operation); + if (typeof onProgress === "function") { + this.onProgress(onProgress); + } + this.intervalInMs = intervalInMs; + } + delay() { + return coreUtil.delay(this.intervalInMs); + } + }; + var cancel = async function cancel2(options = {}) { + const state = this.state; + const { copyId: copyId2 } = state; + if (state.isCompleted) { + return makeBlobBeginCopyFromURLPollOperation(state); + } + if (!copyId2) { + state.isCancelled = true; + return makeBlobBeginCopyFromURLPollOperation(state); + } + await state.blobClient.abortCopyFromURL(copyId2, { + abortSignal: options.abortSignal + }); + state.isCancelled = true; + return makeBlobBeginCopyFromURLPollOperation(state); + }; + var update = async function update2(options = {}) { + const state = this.state; + const { blobClient, copySource: copySource2, startCopyFromURLOptions } = state; + if (!state.isStarted) { + state.isStarted = true; + const result = await blobClient.startCopyFromURL(copySource2, startCopyFromURLOptions); + state.copyId = result.copyId; + if (result.copyStatus === "success") { + state.result = result; + state.isCompleted = true; + } + } else if (!state.isCompleted) { + try { + const result = await state.blobClient.getProperties({ abortSignal: options.abortSignal }); + const { copyStatus, copyProgress } = result; + const prevCopyProgress = state.copyProgress; + if (copyProgress) { + state.copyProgress = copyProgress; + } + if (copyStatus === "pending" && copyProgress !== prevCopyProgress && typeof options.fireProgress === "function") { + options.fireProgress(state); + } else if (copyStatus === "success") { + state.result = result; + state.isCompleted = true; + } else if (copyStatus === "failed") { + state.error = new Error(`Blob copy failed with reason: "${result.copyStatusDescription || "unknown"}"`); + state.isCompleted = true; + } + } catch (err) { + state.error = err; + state.isCompleted = true; + } + } + return makeBlobBeginCopyFromURLPollOperation(state); + }; + var toString2 = function toString3() { + return JSON.stringify({ state: this.state }, (key, value) => { + if (key === "blobClient") { + return void 0; + } + return value; + }); + }; + function makeBlobBeginCopyFromURLPollOperation(state) { + return { + state: Object.assign({}, state), + cancel, + toString: toString2, + update + }; + } + function rangeToString(iRange) { + if (iRange.offset < 0) { + throw new RangeError(`Range.offset cannot be smaller than 0.`); + } + if (iRange.count && iRange.count <= 0) { + throw new RangeError(`Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end.`); + } + return iRange.count ? `bytes=${iRange.offset}-${iRange.offset + iRange.count - 1}` : `bytes=${iRange.offset}-`; + } + var BatchStates; + (function(BatchStates2) { + BatchStates2[BatchStates2["Good"] = 0] = "Good"; + BatchStates2[BatchStates2["Error"] = 1] = "Error"; + })(BatchStates || (BatchStates = {})); + var Batch = class { + /** + * Creates an instance of Batch. + * @param concurrency - + */ + constructor(concurrency = 5) { + this.actives = 0; + this.completed = 0; + this.offset = 0; + this.operations = []; + this.state = BatchStates.Good; + if (concurrency < 1) { + throw new RangeError("concurrency must be larger than 0"); + } + this.concurrency = concurrency; + this.emitter = new events.EventEmitter(); + } + /** + * Add a operation into queue. + * + * @param operation - + */ + addOperation(operation) { + this.operations.push(async () => { + try { + this.actives++; + await operation(); + this.actives--; + this.completed++; + this.parallelExecute(); + } catch (error2) { + this.emitter.emit("error", error2); + } + }); + } + /** + * Start execute operations in the queue. + * + */ + async do() { + if (this.operations.length === 0) { + return Promise.resolve(); + } + this.parallelExecute(); + return new Promise((resolve2, reject) => { + this.emitter.on("finish", resolve2); + this.emitter.on("error", (error2) => { + this.state = BatchStates.Error; + reject(error2); + }); + }); + } + /** + * Get next operation to be executed. Return null when reaching ends. + * + */ + nextOperation() { + if (this.offset < this.operations.length) { + return this.operations[this.offset++]; + } + return null; + } + /** + * Start execute operations. One one the most important difference between + * this method with do() is that do() wraps as an sync method. + * + */ + parallelExecute() { + if (this.state === BatchStates.Error) { + return; + } + if (this.completed >= this.operations.length) { + this.emitter.emit("finish"); + return; + } + while (this.actives < this.concurrency) { + const operation = this.nextOperation(); + if (operation) { + operation(); + } else { + return; + } + } + } + }; + var BuffersStream = class extends stream.Readable { + /** + * Creates an instance of BuffersStream that will emit the data + * contained in the array of buffers. + * + * @param buffers - Array of buffers containing the data + * @param byteLength - The total length of data contained in the buffers + */ + constructor(buffers, byteLength, options) { + super(options); + this.buffers = buffers; + this.byteLength = byteLength; + this.byteOffsetInCurrentBuffer = 0; + this.bufferIndex = 0; + this.pushedBytesLength = 0; + let buffersLength = 0; + for (const buf of this.buffers) { + buffersLength += buf.byteLength; + } + if (buffersLength < this.byteLength) { + throw new Error("Data size shouldn't be larger than the total length of buffers."); + } + } + /** + * Internal _read() that will be called when the stream wants to pull more data in. + * + * @param size - Optional. The size of data to be read + */ + _read(size) { + if (this.pushedBytesLength >= this.byteLength) { + this.push(null); + } + if (!size) { + size = this.readableHighWaterMark; + } + const outBuffers = []; + let i = 0; + while (i < size && this.pushedBytesLength < this.byteLength) { + const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; + const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; + const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); + if (remaining > size - i) { + const end = this.byteOffsetInCurrentBuffer + size - i; + outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); + this.pushedBytesLength += size - i; + this.byteOffsetInCurrentBuffer = end; + i = size; + break; + } else { + const end = this.byteOffsetInCurrentBuffer + remaining; + outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); + if (remaining === remainingCapacityInThisBuffer) { + this.byteOffsetInCurrentBuffer = 0; + this.bufferIndex++; + } else { + this.byteOffsetInCurrentBuffer = end; + } + this.pushedBytesLength += remaining; + i += remaining; + } + } + if (outBuffers.length > 1) { + this.push(Buffer.concat(outBuffers)); + } else if (outBuffers.length === 1) { + this.push(outBuffers[0]); + } + } + }; + var maxBufferLength = buffer.constants.MAX_LENGTH; + var PooledBuffer = class { + /** + * The size of the data contained in the pooled buffers. + */ + get size() { + return this._size; + } + constructor(capacity, buffers, totalLength) { + this.buffers = []; + this.capacity = capacity; + this._size = 0; + const bufferNum = Math.ceil(capacity / maxBufferLength); + for (let i = 0; i < bufferNum; i++) { + let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; + if (len === 0) { + len = maxBufferLength; + } + this.buffers.push(Buffer.allocUnsafe(len)); + } + if (buffers) { + this.fill(buffers, totalLength); + } + } + /** + * Fill the internal buffers with data in the input buffers serially + * with respect to the total length and the total capacity of the internal buffers. + * Data copied will be shift out of the input buffers. + * + * @param buffers - Input buffers containing the data to be filled in the pooled buffer + * @param totalLength - Total length of the data to be filled in. + * + */ + fill(buffers, totalLength) { + this._size = Math.min(this.capacity, totalLength); + let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; + while (totalCopiedNum < this._size) { + const source = buffers[i]; + const target = this.buffers[j]; + const copiedNum = source.copy(target, targetOffset, sourceOffset); + totalCopiedNum += copiedNum; + sourceOffset += copiedNum; + targetOffset += copiedNum; + if (sourceOffset === source.length) { + i++; + sourceOffset = 0; + } + if (targetOffset === target.length) { + j++; + targetOffset = 0; + } + } + buffers.splice(0, i); + if (buffers.length > 0) { + buffers[0] = buffers[0].slice(sourceOffset); + } + } + /** + * Get the readable stream assembled from all the data in the internal buffers. + * + */ + getReadableStream() { + return new BuffersStream(this.buffers, this.size); + } + }; + var BufferScheduler = class { + /** + * Creates an instance of BufferScheduler. + * + * @param readable - A Node.js Readable stream + * @param bufferSize - Buffer size of every maintained buffer + * @param maxBuffers - How many buffers can be allocated + * @param outgoingHandler - An async function scheduled to be + * triggered when a buffer fully filled + * with stream data + * @param concurrency - Concurrency of executing outgoingHandlers (>0) + * @param encoding - [Optional] Encoding of Readable stream when it's a string stream + */ + constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { + this.emitter = new events.EventEmitter(); + this.offset = 0; + this.isStreamEnd = false; + this.isError = false; + this.executingOutgoingHandlers = 0; + this.numBuffers = 0; + this.unresolvedDataArray = []; + this.unresolvedLength = 0; + this.incoming = []; + this.outgoing = []; + if (bufferSize <= 0) { + throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); + } + if (maxBuffers <= 0) { + throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); + } + if (concurrency <= 0) { + throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`); + } + this.bufferSize = bufferSize; + this.maxBuffers = maxBuffers; + this.readable = readable; + this.outgoingHandler = outgoingHandler; + this.concurrency = concurrency; + this.encoding = encoding; + } + /** + * Start the scheduler, will return error when stream of any of the outgoingHandlers + * returns error. + * + */ + async do() { + return new Promise((resolve2, reject) => { + this.readable.on("data", (data) => { + data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; + this.appendUnresolvedData(data); + if (!this.resolveData()) { + this.readable.pause(); + } + }); + this.readable.on("error", (err) => { + this.emitter.emit("error", err); + }); + this.readable.on("end", () => { + this.isStreamEnd = true; + this.emitter.emit("checkEnd"); + }); + this.emitter.on("error", (err) => { + this.isError = true; + this.readable.pause(); + reject(err); + }); + this.emitter.on("checkEnd", () => { + if (this.outgoing.length > 0) { + this.triggerOutgoingHandlers(); + return; + } + if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { + if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { + const buffer2 = this.shiftBufferFromUnresolvedDataArray(); + this.outgoingHandler(() => buffer2.getReadableStream(), buffer2.size, this.offset).then(resolve2).catch(reject); + } else if (this.unresolvedLength >= this.bufferSize) { + return; + } else { + resolve2(); + } + } + }); + }); + } + /** + * Insert a new data into unresolved array. + * + * @param data - + */ + appendUnresolvedData(data) { + this.unresolvedDataArray.push(data); + this.unresolvedLength += data.length; + } + /** + * Try to shift a buffer with size in blockSize. The buffer returned may be less + * than blockSize when data in unresolvedDataArray is less than bufferSize. + * + */ + shiftBufferFromUnresolvedDataArray(buffer2) { + if (!buffer2) { + buffer2 = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); + } else { + buffer2.fill(this.unresolvedDataArray, this.unresolvedLength); + } + this.unresolvedLength -= buffer2.size; + return buffer2; + } + /** + * Resolve data in unresolvedDataArray. For every buffer with size in blockSize + * shifted, it will try to get (or allocate a buffer) from incoming, and fill it, + * then push it into outgoing to be handled by outgoing handler. + * + * Return false when available buffers in incoming are not enough, else true. + * + * @returns Return false when buffers in incoming are not enough, else true. + */ + resolveData() { + while (this.unresolvedLength >= this.bufferSize) { + let buffer2; + if (this.incoming.length > 0) { + buffer2 = this.incoming.shift(); + this.shiftBufferFromUnresolvedDataArray(buffer2); + } else { + if (this.numBuffers < this.maxBuffers) { + buffer2 = this.shiftBufferFromUnresolvedDataArray(); + this.numBuffers++; + } else { + return false; + } + } + this.outgoing.push(buffer2); + this.triggerOutgoingHandlers(); + } + return true; + } + /** + * Try to trigger a outgoing handler for every buffer in outgoing. Stop when + * concurrency reaches. + */ + async triggerOutgoingHandlers() { + let buffer2; + do { + if (this.executingOutgoingHandlers >= this.concurrency) { + return; + } + buffer2 = this.outgoing.shift(); + if (buffer2) { + this.triggerOutgoingHandler(buffer2); + } + } while (buffer2); + } + /** + * Trigger a outgoing handler for a buffer shifted from outgoing. + * + * @param buffer - + */ + async triggerOutgoingHandler(buffer2) { + const bufferLength = buffer2.size; + this.executingOutgoingHandlers++; + this.offset += bufferLength; + try { + await this.outgoingHandler(() => buffer2.getReadableStream(), bufferLength, this.offset - bufferLength); + } catch (err) { + this.emitter.emit("error", err); + return; + } + this.executingOutgoingHandlers--; + this.reuseBuffer(buffer2); + this.emitter.emit("checkEnd"); + } + /** + * Return buffer used by outgoing handler into incoming. + * + * @param buffer - + */ + reuseBuffer(buffer2) { + this.incoming.push(buffer2); + if (!this.isError && this.resolveData() && !this.isStreamEnd) { + this.readable.resume(); + } + } + }; + async function streamToBuffer(stream2, buffer2, offset, end, encoding) { + let pos = 0; + const count = end - offset; + return new Promise((resolve2, reject) => { + const timeout = setTimeout(() => reject(new Error(`The operation cannot be completed in timeout.`)), REQUEST_TIMEOUT); + stream2.on("readable", () => { + if (pos >= count) { + clearTimeout(timeout); + resolve2(); + return; + } + let chunk = stream2.read(); + if (!chunk) { + return; + } + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + const chunkLength = pos + chunk.length > count ? count - pos : chunk.length; + buffer2.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); + pos += chunkLength; + }); + stream2.on("end", () => { + clearTimeout(timeout); + if (pos < count) { + reject(new Error(`Stream drains before getting enough data needed. Data read: ${pos}, data need: ${count}`)); + } + resolve2(); + }); + stream2.on("error", (msg) => { + clearTimeout(timeout); + reject(msg); + }); + }); + } + async function streamToBuffer2(stream2, buffer2, encoding) { + let pos = 0; + const bufferSize = buffer2.length; + return new Promise((resolve2, reject) => { + stream2.on("readable", () => { + let chunk = stream2.read(); + if (!chunk) { + return; + } + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + if (pos + chunk.length > bufferSize) { + reject(new Error(`Stream exceeds buffer size. Buffer size: ${bufferSize}`)); + return; + } + buffer2.fill(chunk, pos, pos + chunk.length); + pos += chunk.length; + }); + stream2.on("end", () => { + resolve2(pos); + }); + stream2.on("error", reject); + }); + } + async function readStreamToLocalFile(rs, file) { + return new Promise((resolve2, reject) => { + const ws = fs__namespace.createWriteStream(file); + rs.on("error", (err) => { + reject(err); + }); + ws.on("error", (err) => { + reject(err); + }); + ws.on("close", resolve2); + rs.pipe(ws); + }); + } + var fsStat = util__namespace.promisify(fs__namespace.stat); + var fsCreateReadStream = fs__namespace.createReadStream; + var BlobClient = class _BlobClient extends StorageClient { + /** + * The name of the blob. + */ + get name() { + return this._name; + } + /** + * The name of the storage container the blob is associated with. + */ + get containerName() { + return this._containerName; + } + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + options = options || {}; + let pipeline; + let url2; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { + url2 = urlOrConnectionString; + if (blobNameOrOptions && typeof blobNameOrOptions !== "string") { + options = blobNameOrOptions; + } + pipeline = newPipeline(new AnonymousCredential(), options); + } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url2 = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + pipeline = newPipeline(sharedKeyCredential, options); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + url2 = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + super(url2, pipeline); + ({ blobName: this._name, containerName: this._containerName } = this.getBlobAndContainerNamesFromUrl()); + this.blobContext = this.storageClientContext.blob; + this._snapshot = getURLParameter(this.url, URLConstants.Parameters.SNAPSHOT); + this._versionId = getURLParameter(this.url, URLConstants.Parameters.VERSIONID); + } + /** + * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. + * + * @param snapshot - The snapshot timestamp. + * @returns A new BlobClient object identical to the source but with the specified snapshot timestamp + */ + withSnapshot(snapshot2) { + return new _BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot2.length === 0 ? void 0 : snapshot2), this.pipeline); + } + /** + * Creates a new BlobClient object pointing to a version of this blob. + * Provide "" will remove the versionId and return a Client to the base blob. + * + * @param versionId - The versionId. + * @returns A new BlobClient object pointing to the version of this blob. + */ + withVersion(versionId2) { + return new _BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId2.length === 0 ? void 0 : versionId2), this.pipeline); + } + /** + * Creates a AppendBlobClient object. + * + */ + getAppendBlobClient() { + return new AppendBlobClient(this.url, this.pipeline); + } + /** + * Creates a BlockBlobClient object. + * + */ + getBlockBlobClient() { + return new BlockBlobClient(this.url, this.pipeline); + } + /** + * Creates a PageBlobClient object. + * + */ + getPageBlobClient() { + return new PageBlobClient(this.url, this.pipeline); + } + /** + * Reads or downloads a blob from the system, including its metadata and properties. + * You can also call Get Blob to read a snapshot. + * + * * In Node.js, data returns in a Readable stream readableStreamBody + * * In browsers, data returns in a promise blobBody + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob + * + * @param offset - From which position of the blob to download, greater than or equal to 0 + * @param count - How much data to be downloaded, greater than 0. Will download to the end when undefined + * @param options - Optional options to Blob Download operation. + * + * + * Example usage (Node.js): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); + * console.log("Downloaded blob content:", downloaded.toString()); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * Example usage (browser): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); + * console.log( + * "Downloaded blob content", + * downloaded + * ); + * + * async function blobToString(blob: Blob): Promise { + * const fileReader = new FileReader(); + * return new Promise((resolve, reject) => { + * fileReader.onloadend = (ev: any) => { + * resolve(ev.target!.result); + * }; + * fileReader.onerror = reject; + * fileReader.readAsText(blob); + * }); + * } + * ``` + */ + async download(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlobClient-download", options, async (updatedOptions) => { + var _a; + const res = assertResponse(await this.blobContext.download({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + requestOptions: { + onDownloadProgress: coreUtil.isNode ? void 0 : options.onProgress + // for Node.js, progress is reported by RetriableReadableStream + }, + range: offset === 0 && !count ? void 0 : rangeToString({ offset, count }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey, + tracingOptions: updatedOptions.tracingOptions + })); + const wrappedRes = Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); + if (!coreUtil.isNode) { + return wrappedRes; + } + if (options.maxRetryRequests === void 0 || options.maxRetryRequests < 0) { + options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; + } + if (res.contentLength === void 0) { + throw new RangeError(`File download response doesn't contain valid content length header`); + } + if (!res.etag) { + throw new RangeError(`File download response doesn't contain valid etag header`); + } + return new BlobDownloadResponse(wrappedRes, async (start) => { + var _a2; + const updatedDownloadOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res.etag, + ifModifiedSince: options.conditions.ifModifiedSince, + ifNoneMatch: options.conditions.ifNoneMatch, + ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, + ifTags: (_a2 = options.conditions) === null || _a2 === void 0 ? void 0 : _a2.tagConditions + }, + range: rangeToString({ + count: offset + res.contentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey + }; + return (await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal }, updatedDownloadOptions))).readableStreamBody; + }, offset, res.contentLength, { + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress + }); + }); + } + /** + * Returns true if the Azure blob resource represented by this client exists; false otherwise. + * + * NOTE: use this function with care since an existing blob might be deleted by other clients or + * applications. Vice versa new blobs might be added by other clients or applications after this + * function completes. + * + * @param options - options to Exists operation. + */ + async exists(options = {}) { + return tracingClient.withSpan("BlobClient-exists", options, async (updatedOptions) => { + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + await this.getProperties({ + abortSignal: options.abortSignal, + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + }); + return true; + } catch (e) { + if (e.statusCode === 404) { + return false; + } else if (e.statusCode === 409 && (e.details.errorCode === BlobUsesCustomerSpecifiedEncryptionMsg || e.details.errorCode === BlobDoesNotUseCustomerSpecifiedEncryption)) { + return true; + } + throw e; + } + }); + } + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties + * for the blob. It does not return the content of the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties + * + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which + * will retain their original casing. + * + * @param options - Optional options to Get Properties operation. + */ + async getProperties(options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlobClient-getProperties", options, async (updatedOptions) => { + var _a; + const res = assertResponse(await this.blobContext.getProperties({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + tracingOptions: updatedOptions.tracingOptions + })); + return Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); + }); + } + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param options - Optional options to Blob Delete operation. + */ + async delete(options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("BlobClient-delete", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.blobContext.delete({ + abortSignal: options.abortSignal, + deleteSnapshots: options.deleteSnapshots, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param options - Optional options to Blob Delete operation. + */ + async deleteIfExists(options = {}) { + return tracingClient.withSpan("BlobClient-deleteIfExists", options, async (updatedOptions) => { + var _a, _b; + try { + const res = assertResponse(await this.delete(updatedOptions)); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + throw e; + } + }); + } + /** + * Restores the contents and metadata of soft deleted blob and any associated + * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 + * or later. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob + * + * @param options - Optional options to Blob Undelete operation. + */ + async undelete(options = {}) { + return tracingClient.withSpan("BlobClient-undelete", options, async (updatedOptions) => { + return assertResponse(await this.blobContext.undelete({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Sets system properties on the blob. + * + * If no value provided, or no value provided for the specified blob HTTP headers, + * these blob HTTP headers without a value will be cleared. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * + * @param blobHTTPHeaders - If no value provided, or no value provided for + * the specified blob HTTP headers, these blob HTTP + * headers without a value will be cleared. + * A common header to set is `blobContentType` + * enabling the browser to provide functionality + * based on file type. + * @param options - Optional options to Blob Set HTTP Headers operation. + */ + async setHTTPHeaders(blobHTTPHeaders, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlobClient-setHTTPHeaders", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.blobContext.setHttpHeaders({ + abortSignal: options.abortSignal, + blobHttpHeaders: blobHTTPHeaders, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + // cpkInfo: options.customerProvidedKey, // CPK is not included in Swagger, should change this back when this issue is fixed in Swagger. + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Sets user-defined metadata for the specified blob as one or more name-value pairs. + * + * If no option provided, or no metadata defined in the parameter, the blob + * metadata will be removed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata + * + * @param metadata - Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param options - Optional options to Set Metadata operation. + */ + async setMetadata(metadata2, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlobClient-setMetadata", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.blobContext.setMetadata({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: metadata2, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Sets tags on the underlying blob. + * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. + * Valid tag key and value characters include lower and upper case letters, digits (0-9), + * space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_'). + * + * @param tags - + * @param options - + */ + async setTags(tags2, options = {}) { + return tracingClient.withSpan("BlobClient-setTags", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.blobContext.setTags({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + tracingOptions: updatedOptions.tracingOptions, + tags: toBlobTags(tags2) + })); + }); + } + /** + * Gets the tags associated with the underlying blob. + * + * @param options - + */ + async getTags(options = {}) { + return tracingClient.withSpan("BlobClient-getTags", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this.blobContext.getTags({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + })); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); + return wrappedResponse; + }); + } + /** + * Get a {@link BlobLeaseClient} that manages leases on the blob. + * + * @param proposeLeaseId - Initial proposed lease Id. + * @returns A new BlobLeaseClient object for managing leases on the blob. + */ + getBlobLeaseClient(proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); + } + /** + * Creates a read-only snapshot of a blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob + * + * @param options - Optional options to the Blob Create Snapshot operation. + */ + async createSnapshot(options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlobClient-createSnapshot", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.blobContext.createSnapshot({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Asynchronously copies a blob to a destination within the storage account. + * This method returns a long running operation poller that allows you to wait + * indefinitely until the copy is completed. + * You can also cancel a copy before it is completed by calling `cancelOperation` on the poller. + * Note that the onProgress callback will not be invoked if the operation completes in the first + * request, and attempting to cancel a completed copy will result in an error being thrown. + * + * In version 2012-02-12 and later, the source for a Copy Blob operation can be + * a committed blob in any Azure storage account. + * Beginning with version 2015-02-21, the source for a Copy Blob operation can be + * an Azure file in any Azure storage account. + * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob + * operation to copy from another storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + * + * Example using automatic polling: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using manual polling: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * while (!poller.isDone()) { + * await poller.poll(); + * } + * const result = copyPoller.getResult(); + * ``` + * + * Example using progress updates: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url', { + * onProgress(state) { + * console.log(`Progress: ${state.copyProgress}`); + * } + * }); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using a changing polling interval (default 15 seconds): + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url', { + * intervalInMs: 1000 // poll blob every 1 second for copy progress + * }); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using copy cancellation: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * // cancel operation after starting it. + * try { + * await copyPoller.cancelOperation(); + * // calls to get the result now throw PollerCancelledError + * await copyPoller.getResult(); + * } catch (err) { + * if (err.name === 'PollerCancelledError') { + * console.log('The copy was cancelled.'); + * } + * } + * ``` + * + * @param copySource - url to the source Azure Blob/File. + * @param options - Optional options to the Blob Start Copy From URL operation. + */ + async beginCopyFromURL(copySource2, options = {}) { + const client = { + abortCopyFromURL: (...args) => this.abortCopyFromURL(...args), + getProperties: (...args) => this.getProperties(...args), + startCopyFromURL: (...args) => this.startCopyFromURL(...args) + }; + const poller = new BlobBeginCopyFromUrlPoller({ + blobClient: client, + copySource: copySource2, + intervalInMs: options.intervalInMs, + onProgress: options.onProgress, + resumeFrom: options.resumeFrom, + startCopyFromURLOptions: options + }); + await poller.poll(); + return poller; + } + /** + * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero + * length and full metadata. Version 2012-02-12 and newer. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob + * + * @param copyId - Id of the Copy From URL operation. + * @param options - Optional options to the Blob Abort Copy From URL operation. + */ + async abortCopyFromURL(copyId2, options = {}) { + return tracingClient.withSpan("BlobClient-abortCopyFromURL", options, async (updatedOptions) => { + return assertResponse(await this.blobContext.abortCopyFromURL(copyId2, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not + * return a response until the copy is complete. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url + * + * @param copySource - The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication + * @param options - + */ + async syncCopyFromURL(copySource2, options = {}) { + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + return tracingClient.withSpan("BlobClient-syncCopyFromURL", options, async (updatedOptions) => { + var _a, _b, _c, _d, _e, _f, _g; + return assertResponse(await this.blobContext.copyFromURL(copySource2, { + abortSignal: options.abortSignal, + metadata: options.metadata, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, + sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, + sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, + sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince + }, + sourceContentMD5: options.sourceContentMD5, + copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + immutabilityPolicyExpiry: (_f = options.immutabilityPolicy) === null || _f === void 0 ? void 0 : _f.expiriesOn, + immutabilityPolicyMode: (_g = options.immutabilityPolicy) === null || _g === void 0 ? void 0 : _g.policyMode, + legalHold: options.legalHold, + encryptionScope: options.encryptionScope, + copySourceTags: options.copySourceTags, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Sets the tier on a blob. The operation is allowed on a page blob in a premium + * storage account and on a block blob in a blob storage account (locally redundant + * storage only). A premium page blob's tier determines the allowed size, IOPS, + * and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive + * storage type. This operation does not update the blob's ETag. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier + * + * @param tier - The tier to be set on the blob. Valid values are Hot, Cool, or Archive. + * @param options - Optional options to the Blob Set Tier operation. + */ + async setAccessTier(tier2, options = {}) { + return tracingClient.withSpan("BlobClient-setAccessTier", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.blobContext.setTier(toAccessTier(tier2), { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + rehydratePriority: options.rehydratePriority, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + async downloadToBuffer(param1, param2, param3, param4 = {}) { + var _a; + let buffer2; + let offset = 0; + let count = 0; + let options = param4; + if (param1 instanceof Buffer) { + buffer2 = param1; + offset = param2 || 0; + count = typeof param3 === "number" ? param3 : 0; + } else { + offset = typeof param1 === "number" ? param1 : 0; + count = typeof param2 === "number" ? param2 : 0; + options = param3 || {}; + } + let blockSize = (_a = options.blockSize) !== null && _a !== void 0 ? _a : 0; + if (blockSize < 0) { + throw new RangeError("blockSize option must be >= 0"); + } + if (blockSize === 0) { + blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + if (offset < 0) { + throw new RangeError("offset option must be >= 0"); + } + if (count && count <= 0) { + throw new RangeError("count option must be greater than 0"); + } + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("BlobClient-downloadToBuffer", options, async (updatedOptions) => { + if (!count) { + const response = await this.getProperties(Object.assign(Object.assign({}, options), { tracingOptions: updatedOptions.tracingOptions })); + count = response.contentLength - offset; + if (count < 0) { + throw new RangeError(`offset ${offset} shouldn't be larger than blob size ${response.contentLength}`); + } + } + if (!buffer2) { + try { + buffer2 = Buffer.alloc(count); + } catch (error2) { + throw new Error(`Unable to allocate the buffer of size: ${count}(in bytes). Please try passing your own buffer to the "downloadToBuffer" method or try using other methods like "download" or "downloadToFile". ${error2.message}`); + } + } + if (buffer2.length < count) { + throw new RangeError(`The buffer's size should be equal to or larger than the request count of bytes: ${count}`); + } + let transferProgress = 0; + const batch = new Batch(options.concurrency); + for (let off = offset; off < offset + count; off = off + blockSize) { + batch.addOperation(async () => { + let chunkEnd = offset + count; + if (off + blockSize < chunkEnd) { + chunkEnd = off + blockSize; + } + const response = await this.download(off, chunkEnd - off, { + abortSignal: options.abortSignal, + conditions: options.conditions, + maxRetryRequests: options.maxRetryRequestsPerBlock, + customerProvidedKey: options.customerProvidedKey, + tracingOptions: updatedOptions.tracingOptions + }); + const stream2 = response.readableStreamBody; + await streamToBuffer(stream2, buffer2, off - offset, chunkEnd - offset); + transferProgress += chunkEnd - off; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress }); + } + }); + } + await batch.do(); + return buffer2; + }); + } + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Downloads an Azure Blob to a local file. + * Fails if the the given file path already exits. + * Offset and count are optional, pass 0 and undefined respectively to download the entire blob. + * + * @param filePath - + * @param offset - From which position of the block blob to download. + * @param count - How much data to be downloaded. Will download to the end when passing undefined. + * @param options - Options to Blob download options. + * @returns The response data for blob download operation, + * but with readableStreamBody set to undefined since its + * content is already read and written into a local file + * at the specified path. + */ + async downloadToFile(filePath, offset = 0, count, options = {}) { + return tracingClient.withSpan("BlobClient-downloadToFile", options, async (updatedOptions) => { + const response = await this.download(offset, count, Object.assign(Object.assign({}, options), { tracingOptions: updatedOptions.tracingOptions })); + if (response.readableStreamBody) { + await readStreamToLocalFile(response.readableStreamBody, filePath); + } + response.blobDownloadStream = void 0; + return response; + }); + } + getBlobAndContainerNamesFromUrl() { + let containerName; + let blobName; + try { + const parsedUrl = new URL(this.url); + if (parsedUrl.host.split(".")[1] === "blob") { + const pathComponents = parsedUrl.pathname.match("/([^/]*)(/(.*))?"); + containerName = pathComponents[1]; + blobName = pathComponents[3]; + } else if (isIpEndpointStyle(parsedUrl)) { + const pathComponents = parsedUrl.pathname.match("/([^/]*)/([^/]*)(/(.*))?"); + containerName = pathComponents[2]; + blobName = pathComponents[4]; + } else { + const pathComponents = parsedUrl.pathname.match("/([^/]*)(/(.*))?"); + containerName = pathComponents[1]; + blobName = pathComponents[3]; + } + containerName = decodeURIComponent(containerName); + blobName = decodeURIComponent(blobName); + blobName = blobName.replace(/\\/g, "/"); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return { blobName, containerName }; + } catch (error2) { + throw new Error("Unable to extract blobName and containerName with provided information."); + } + } + /** + * Asynchronously copies a blob to a destination within the storage account. + * In version 2012-02-12 and later, the source for a Copy Blob operation can be + * a committed blob in any Azure storage account. + * Beginning with version 2015-02-21, the source for a Copy Blob operation can be + * an Azure file in any Azure storage account. + * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob + * operation to copy from another storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + * + * @param copySource - url to the source Azure Blob/File. + * @param options - Optional options to the Blob Start Copy From URL operation. + */ + async startCopyFromURL(copySource2, options = {}) { + return tracingClient.withSpan("BlobClient-startCopyFromURL", options, async (updatedOptions) => { + var _a, _b, _c; + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + return assertResponse(await this.blobContext.startCopyFromURL(copySource2, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, + sourceIfTags: options.sourceConditions.tagConditions + }, + immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, + immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, + legalHold: options.legalHold, + rehydratePriority: options.rehydratePriority, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + sealBlob: options.sealBlob, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Only available for BlobClient constructed with a shared key credential. + * + * Generates a Blob Service Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateSasUrl(options) { + return new Promise((resolve2) => { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), this.credential).toString(); + resolve2(appendToURLQuery(this.url, sas)); + }); + } + /** + * Only available for BlobClient constructed with a shared key credential. + * + * Generates string to sign for a Blob Service Shared Access Signature (SAS) URI based on + * the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + generateSasStringToSign(options) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), this.credential).stringToSign; + } + /** + * Delete the immutablility policy on the blob. + * + * @param options - Optional options to delete immutability policy on the blob. + */ + async deleteImmutabilityPolicy(options = {}) { + return tracingClient.withSpan("BlobClient-deleteImmutabilityPolicy", options, async (updatedOptions) => { + return assertResponse(await this.blobContext.deleteImmutabilityPolicy({ + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Set immutability policy on the blob. + * + * @param options - Optional options to set immutability policy on the blob. + */ + async setImmutabilityPolicy(immutabilityPolicy, options = {}) { + return tracingClient.withSpan("BlobClient-setImmutabilityPolicy", options, async (updatedOptions) => { + return assertResponse(await this.blobContext.setImmutabilityPolicy({ + immutabilityPolicyExpiry: immutabilityPolicy.expiriesOn, + immutabilityPolicyMode: immutabilityPolicy.policyMode, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Set legal hold on the blob. + * + * @param options - Optional options to set legal hold on the blob. + */ + async setLegalHold(legalHoldEnabled, options = {}) { + return tracingClient.withSpan("BlobClient-setLegalHold", options, async (updatedOptions) => { + return assertResponse(await this.blobContext.setLegalHold(legalHoldEnabled, { + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * + * @param options - Options to the Service Get Account Info operation. + * @returns Response data for the Service Get Account Info operation. + */ + async getAccountInfo(options = {}) { + return tracingClient.withSpan("BlobClient-getAccountInfo", options, async (updatedOptions) => { + return assertResponse(await this.blobContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + }; + var AppendBlobClient = class _AppendBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + let pipeline; + let url2; + options = options || {}; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { + url2 = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url2 = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + pipeline = newPipeline(sharedKeyCredential, options); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + url2 = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + super(url2, pipeline); + this.appendBlobContext = this.storageClientContext.appendBlob; + } + /** + * Creates a new AppendBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. + * + * @param snapshot - The snapshot timestamp. + * @returns A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. + */ + withSnapshot(snapshot2) { + return new _AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot2.length === 0 ? void 0 : snapshot2), this.pipeline); + } + /** + * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param options - Options to the Append Block Create operation. + * + * + * Example usage: + * + * ```js + * const appendBlobClient = containerClient.getAppendBlobClient(""); + * await appendBlobClient.create(); + * ``` + */ + async create(options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("AppendBlobClient-create", options, async (updatedOptions) => { + var _a, _b, _c; + return assertResponse(await this.appendBlobContext.create(0, { + abortSignal: options.abortSignal, + blobHttpHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, + immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, + legalHold: options.legalHold, + blobTagsString: toBlobTagsString(options.tags), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. + * If the blob with the same name already exists, the content of the existing blob will remain unchanged. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param options - + */ + async createIfNotExists(options = {}) { + const conditions = { ifNoneMatch: ETagAny }; + return tracingClient.withSpan("AppendBlobClient-createIfNotExists", options, async (updatedOptions) => { + var _a, _b; + try { + const res = assertResponse(await this.create(Object.assign(Object.assign({}, updatedOptions), { conditions }))); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + throw e; + } + }); + } + /** + * Seals the append blob, making it read only. + * + * @param options - + */ + async seal(options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("AppendBlobClient-seal", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.appendBlobContext.seal({ + abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Commits a new block of data to the end of the existing append blob. + * @see https://docs.microsoft.com/rest/api/storageservices/append-block + * + * @param body - Data to be appended. + * @param contentLength - Length of the body in bytes. + * @param options - Options to the Append Block operation. + * + * + * Example usage: + * + * ```js + * const content = "Hello World!"; + * + * // Create a new append blob and append data to the blob. + * const newAppendBlobClient = containerClient.getAppendBlobClient(""); + * await newAppendBlobClient.create(); + * await newAppendBlobClient.appendBlock(content, content.length); + * + * // Append data to an existing append blob. + * const existingAppendBlobClient = containerClient.getAppendBlobClient(""); + * await existingAppendBlobClient.appendBlock(content, content.length); + * ``` + */ + async appendBlock(body2, contentLength2, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("AppendBlobClient-appendBlock", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.appendBlobContext.appendBlock(contentLength2, body2, { + abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + requestOptions: { + onUploadProgress: options.onProgress + }, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * The Append Block operation commits a new block of data to the end of an existing append blob + * where the contents are read from a source url. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url + * + * @param sourceURL - + * The url to the blob that will be the source of the copy. A source blob in the same storage account can + * be authenticated via Shared Key. However, if the source is a blob in another account, the source blob + * must either be public or must be authenticated via a shared access signature. If the source blob is + * public, no authentication is required to perform the operation. + * @param sourceOffset - Offset in source to be appended + * @param count - Number of bytes to be appended as a block + * @param options - + */ + async appendBlockFromURL(sourceURL, sourceOffset, count, options = {}) { + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("AppendBlobClient-appendBlockFromURL", options, async (updatedOptions) => { + var _a, _b, _c, _d, _e; + return assertResponse(await this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { + abortSignal: options.abortSignal, + sourceRange: rangeToString({ offset: sourceOffset, count }), + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + appendPositionAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, + sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, + sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, + sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince + }, + copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + }; + var BlockBlobClient = class _BlockBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + let pipeline; + let url2; + options = options || {}; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { + url2 = urlOrConnectionString; + if (blobNameOrOptions && typeof blobNameOrOptions !== "string") { + options = blobNameOrOptions; + } + pipeline = newPipeline(new AnonymousCredential(), options); + } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url2 = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + pipeline = newPipeline(sharedKeyCredential, options); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + url2 = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + super(url2, pipeline); + this.blockBlobContext = this.storageClientContext.blockBlob; + this._blobContext = this.storageClientContext.blob; + } + /** + * Creates a new BlockBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a URL to the base blob. + * + * @param snapshot - The snapshot timestamp. + * @returns A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. + */ + withSnapshot(snapshot2) { + return new _BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot2.length === 0 ? void 0 : snapshot2), this.pipeline); + } + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Quick query for a JSON or CSV formatted blob. + * + * Example usage (Node.js): + * + * ```js + * // Query and convert a blob to a string + * const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage"); + * const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString(); + * console.log("Query blob content:", downloaded); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * @param query - + * @param options - + */ + async query(query, options = {}) { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + if (!coreUtil.isNode) { + throw new Error("This operation currently is only supported in Node.js."); + } + return tracingClient.withSpan("BlockBlobClient-query", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this._blobContext.query({ + abortSignal: options.abortSignal, + queryRequest: { + queryType: "SQL", + expression: query, + inputSerialization: toQuerySerialization(options.inputTextConfiguration), + outputSerialization: toQuerySerialization(options.outputTextConfiguration) + }, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + tracingOptions: updatedOptions.tracingOptions + })); + return new BlobQueryResponse(response, { + abortSignal: options.abortSignal, + onProgress: options.onProgress, + onError: options.onError + }); + }); + } + /** + * Creates a new block blob, or updates the content of an existing block blob. + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link stageBlock} and {@link commitBlockList}. + * + * This is a non-parallel uploading method, please use {@link uploadFile}, + * {@link uploadStream} or {@link uploadBrowserData} for better performance + * with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param options - Options to the Block Blob Upload operation. + * @returns Response data for the Block Blob Upload operation. + * + * Example usage: + * + * ```js + * const content = "Hello world!"; + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); + * ``` + */ + async upload(body2, contentLength2, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlockBlobClient-upload", options, async (updatedOptions) => { + var _a, _b, _c; + return assertResponse(await this.blockBlobContext.upload(contentLength2, body2, { + abortSignal: options.abortSignal, + blobHttpHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + requestOptions: { + onUploadProgress: options.onProgress + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, + immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, + legalHold: options.legalHold, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Creates a new Block Blob where the contents of the blob are read from a given URL. + * This API is supported beginning with the 2020-04-08 version. Partial updates + * are not supported with Put Blob from URL; the content of an existing blob is overwritten with + * the content of the new blob. To perform partial updates to a block blob’s contents using a + * source URL, use {@link stageBlockFromURL} and {@link commitBlockList}. + * + * @param sourceURL - Specifies the URL of the blob. The value + * may be a URL of up to 2 KB in length that specifies a blob. + * The value should be URL-encoded as it would appear + * in a request URI. The source blob must either be public + * or must be authenticated via a shared access signature. + * If the source blob is public, no authentication is required + * to perform the operation. Here are some examples of source object URLs: + * - https://myaccount.blob.core.windows.net/mycontainer/myblob + * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param options - Optional parameters. + */ + async syncUploadFromURL(sourceURL, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlockBlobClient-syncUploadFromURL", options, async (updatedOptions) => { + var _a, _b, _c, _d, _e, _f; + return assertResponse(await this.blockBlobContext.putBlobFromUrl(0, sourceURL, Object.assign(Object.assign({}, options), { blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, + sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, + sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, + sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince, + sourceIfTags: (_f = options.sourceConditions) === null || _f === void 0 ? void 0 : _f.tagConditions + }, cpkInfo: options.customerProvidedKey, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), copySourceTags: options.copySourceTags, tracingOptions: updatedOptions.tracingOptions }))); + }); + } + /** + * Uploads the specified block to the block blob's "staging area" to be later + * committed by a call to commitBlockList. + * @see https://docs.microsoft.com/rest/api/storageservices/put-block + * + * @param blockId - A 64-byte value that is base64-encoded + * @param body - Data to upload to the staging area. + * @param contentLength - Number of bytes to upload. + * @param options - Options to the Block Blob Stage Block operation. + * @returns Response data for the Block Blob Stage Block operation. + */ + async stageBlock(blockId2, body2, contentLength2, options = {}) { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlockBlobClient-stageBlock", options, async (updatedOptions) => { + return assertResponse(await this.blockBlobContext.stageBlock(blockId2, contentLength2, body2, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + requestOptions: { + onUploadProgress: options.onProgress + }, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * The Stage Block From URL operation creates a new block to be committed as part + * of a blob where the contents are read from a URL. + * This API is available starting in version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url + * + * @param blockId - A 64-byte value that is base64-encoded + * @param sourceURL - Specifies the URL of the blob. The value + * may be a URL of up to 2 KB in length that specifies a blob. + * The value should be URL-encoded as it would appear + * in a request URI. The source blob must either be public + * or must be authenticated via a shared access signature. + * If the source blob is public, no authentication is required + * to perform the operation. Here are some examples of source object URLs: + * - https://myaccount.blob.core.windows.net/mycontainer/myblob + * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param offset - From which position of the blob to download, greater than or equal to 0 + * @param count - How much data to be downloaded, greater than 0. Will download to the end when undefined + * @param options - Options to the Block Blob Stage Block From URL operation. + * @returns Response data for the Block Blob Stage Block From URL operation. + */ + async stageBlockFromURL(blockId2, sourceURL, offset = 0, count, options = {}) { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlockBlobClient-stageBlockFromURL", options, async (updatedOptions) => { + return assertResponse(await this.blockBlobContext.stageBlockFromURL(blockId2, 0, sourceURL, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + sourceRange: offset === 0 && !count ? void 0 : rangeToString({ offset, count }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written + * to the server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to + * update a blob by uploading only those blocks that have changed, then committing the new and existing + * blocks together. Any blocks not specified in the block list and permanently deleted. + * @see https://docs.microsoft.com/rest/api/storageservices/put-block-list + * + * @param blocks - Array of 64-byte value that is base64-encoded + * @param options - Options to the Block Blob Commit Block List operation. + * @returns Response data for the Block Blob Commit Block List operation. + */ + async commitBlockList(blocks2, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("BlockBlobClient-commitBlockList", options, async (updatedOptions) => { + var _a, _b, _c; + return assertResponse(await this.blockBlobContext.commitBlockList({ latest: blocks2 }, { + abortSignal: options.abortSignal, + blobHttpHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, + immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, + legalHold: options.legalHold, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns the list of blocks that have been uploaded as part of a block blob + * using the specified block list filter. + * @see https://docs.microsoft.com/rest/api/storageservices/get-block-list + * + * @param listType - Specifies whether to return the list of committed blocks, + * the list of uncommitted blocks, or both lists together. + * @param options - Options to the Block Blob Get Block List operation. + * @returns Response data for the Block Blob Get Block List operation. + */ + async getBlockList(listType2, options = {}) { + return tracingClient.withSpan("BlockBlobClient-getBlockList", options, async (updatedOptions) => { + var _a; + const res = assertResponse(await this.blockBlobContext.getBlockList(listType2, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + })); + if (!res.committedBlocks) { + res.committedBlocks = []; + } + if (!res.uncommittedBlocks) { + res.uncommittedBlocks = []; + } + return res; + }); + } + // High level functions + /** + * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. + * + * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is + * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is + * `blobContentType`, enabling the browser to provide + * functionality based on file type. + * + * @param data - Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView + * @param options - + */ + async uploadData(data, options = {}) { + return tracingClient.withSpan("BlockBlobClient-uploadData", options, async (updatedOptions) => { + if (coreUtil.isNode) { + let buffer2; + if (data instanceof Buffer) { + buffer2 = data; + } else if (data instanceof ArrayBuffer) { + buffer2 = Buffer.from(data); + } else { + data = data; + buffer2 = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } + return this.uploadSeekableInternal((offset, size) => buffer2.slice(offset, offset + size), buffer2.byteLength, updatedOptions); + } else { + const browserBlob = new Blob([data]); + return this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); + } + }); + } + /** + * ONLY AVAILABLE IN BROWSERS. + * + * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. + * + * When buffer length lesser than or equal to 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call + * {@link commitBlockList} to commit the block list. + * + * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is + * `blobContentType`, enabling the browser to provide + * functionality based on file type. + * + * @deprecated Use {@link uploadData} instead. + * + * @param browserData - Blob, File, ArrayBuffer or ArrayBufferView + * @param options - Options to upload browser data. + * @returns Response data for the Blob Upload operation. + */ + async uploadBrowserData(browserData, options = {}) { + return tracingClient.withSpan("BlockBlobClient-uploadBrowserData", options, async (updatedOptions) => { + const browserBlob = new Blob([browserData]); + return this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); + }); + } + /** + * + * Uploads data to block blob. Requires a bodyFactory as the data source, + * which need to return a {@link HttpRequestBody} object with the offset and size provided. + * + * When data length is no more than the specified {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is + * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * @param bodyFactory - + * @param size - size of the data to upload. + * @param options - Options to Upload to Block Blob operation. + * @returns Response data for the Blob Upload operation. + */ + async uploadSeekableInternal(bodyFactory, size, options = {}) { + var _a, _b; + let blockSize = (_a = options.blockSize) !== null && _a !== void 0 ? _a : 0; + if (blockSize < 0 || blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError(`blockSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES}`); + } + const maxSingleShotSize = (_b = options.maxSingleShotSize) !== null && _b !== void 0 ? _b : BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; + if (maxSingleShotSize < 0 || maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { + throw new RangeError(`maxSingleShotSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}`); + } + if (blockSize === 0) { + if (size > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError(`${size} is too larger to upload to a block blob.`); + } + if (size > maxSingleShotSize) { + blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); + if (blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { + blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + } + } + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("BlockBlobClient-uploadSeekableInternal", options, async (updatedOptions) => { + if (size <= maxSingleShotSize) { + return assertResponse(await this.upload(bodyFactory(0, size), size, updatedOptions)); + } + const numBlocks = Math.floor((size - 1) / blockSize) + 1; + if (numBlocks > BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError(`The buffer's size is too big or the BlockSize is too small;the number of blocks must be <= ${BLOCK_BLOB_MAX_BLOCKS}`); + } + const blockList = []; + const blockIDPrefix = coreUtil.randomUUID(); + let transferProgress = 0; + const batch = new Batch(options.concurrency); + for (let i = 0; i < numBlocks; i++) { + batch.addOperation(async () => { + const blockID = generateBlockID(blockIDPrefix, i); + const start = blockSize * i; + const end = i === numBlocks - 1 ? size : start + blockSize; + const contentLength2 = end - start; + blockList.push(blockID); + await this.stageBlock(blockID, bodyFactory(start, contentLength2), contentLength2, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }); + transferProgress += contentLength2; + if (options.onProgress) { + options.onProgress({ + loadedBytes: transferProgress + }); + } + }); + } + await batch.do(); + return this.commitBlockList(blockList, updatedOptions); + }); + } + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Uploads a local file in blocks to a block blob. + * + * When file size lesser than or equal to 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList + * to commit the block list. + * + * @param filePath - Full path of local file + * @param options - Options to Upload to Block Blob operation. + * @returns Response data for the Blob Upload operation. + */ + async uploadFile(filePath, options = {}) { + return tracingClient.withSpan("BlockBlobClient-uploadFile", options, async (updatedOptions) => { + const size = (await fsStat(filePath)).size; + return this.uploadSeekableInternal((offset, count) => { + return () => fsCreateReadStream(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); + }, size, Object.assign(Object.assign({}, options), { tracingOptions: updatedOptions.tracingOptions })); + }); + } + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Uploads a Node.js Readable stream into block blob. + * + * PERFORMANCE IMPROVEMENT TIPS: + * * Input stream highWaterMark is better to set a same value with bufferSize + * parameter, which will avoid Buffer.concat() operations. + * + * @param stream - Node.js Readable stream + * @param bufferSize - Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB + * @param maxConcurrency - Max concurrency indicates the max number of buffers that can be allocated, + * positive correlation with max uploading concurrency. Default value is 5 + * @param options - Options to Upload Stream to Block Blob operation. + * @returns Response data for the Blob Upload operation. + */ + async uploadStream(stream2, bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) { + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("BlockBlobClient-uploadStream", options, async (updatedOptions) => { + let blockNum = 0; + const blockIDPrefix = coreUtil.randomUUID(); + let transferProgress = 0; + const blockList = []; + const scheduler = new BufferScheduler( + stream2, + bufferSize, + maxConcurrency, + async (body2, length) => { + const blockID = generateBlockID(blockIDPrefix, blockNum); + blockList.push(blockID); + blockNum++; + await this.stageBlock(blockID, body2, length, { + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }); + transferProgress += length; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress }); + } + }, + // concurrency should set a smaller value than maxConcurrency, which is helpful to + // reduce the possibility when a outgoing handler waits for stream data, in + // this situation, outgoing handlers are blocked. + // Outgoing queue shouldn't be empty. + Math.ceil(maxConcurrency / 4 * 3) + ); + await scheduler.do(); + return assertResponse(await this.commitBlockList(blockList, Object.assign(Object.assign({}, options), { tracingOptions: updatedOptions.tracingOptions }))); + }); + } + }; + var PageBlobClient = class _PageBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + let pipeline; + let url2; + options = options || {}; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { + url2 = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url2 = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + pipeline = newPipeline(sharedKeyCredential, options); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + url2 = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + super(url2, pipeline); + this.pageBlobContext = this.storageClientContext.pageBlob; + } + /** + * Creates a new PageBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. + * + * @param snapshot - The snapshot timestamp. + * @returns A new PageBlobClient object identical to the source but with the specified snapshot timestamp. + */ + withSnapshot(snapshot2) { + return new _PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot2.length === 0 ? void 0 : snapshot2), this.pipeline); + } + /** + * Creates a page blob of the specified length. Call uploadPages to upload data + * data to a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param size - size of the page blob. + * @param options - Options to the Page Blob Create operation. + * @returns Response data for the Page Blob Create operation. + */ + async create(size, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("PageBlobClient-create", options, async (updatedOptions) => { + var _a, _b, _c; + return assertResponse(await this.pageBlobContext.create(0, size, { + abortSignal: options.abortSignal, + blobHttpHeaders: options.blobHTTPHeaders, + blobSequenceNumber: options.blobSequenceNumber, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, + immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, + legalHold: options.legalHold, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Creates a page blob of the specified length. Call uploadPages to upload data + * data to a page blob. If the blob with the same name already exists, the content + * of the existing blob will remain unchanged. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param size - size of the page blob. + * @param options - + */ + async createIfNotExists(size, options = {}) { + return tracingClient.withSpan("PageBlobClient-createIfNotExists", options, async (updatedOptions) => { + var _a, _b; + try { + const conditions = { ifNoneMatch: ETagAny }; + const res = assertResponse(await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }))); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + throw e; + } + }); + } + /** + * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * + * @param body - Data to upload + * @param offset - Offset of destination page blob + * @param count - Content length of the body, also number of bytes to be uploaded + * @param options - Options to the Page Blob Upload Pages operation. + * @returns Response data for the Page Blob Upload Pages operation. + */ + async uploadPages(body2, offset, count, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("PageBlobClient-uploadPages", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.uploadPages(count, body2, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + requestOptions: { + onUploadProgress: options.onProgress + }, + range: rangeToString({ offset, count }), + sequenceNumberAccessConditions: options.conditions, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * The Upload Pages operation writes a range of pages to a page blob where the + * contents are read from a URL. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url + * + * @param sourceURL - Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication + * @param sourceOffset - The source offset to copy from. Pass 0 to copy from the beginning of source page blob + * @param destOffset - Offset of destination page blob + * @param count - Number of bytes to be uploaded from source page blob + * @param options - + */ + async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("PageBlobClient-uploadPagesFromURL", options, async (updatedOptions) => { + var _a, _b, _c, _d, _e; + return assertResponse(await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), { + abortSignal: options.abortSignal, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + sequenceNumberAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, + sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, + sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, + sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Frees the specified pages from the page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * + * @param offset - Starting byte position of the pages to clear. + * @param count - Number of bytes to clear. + * @param options - Options to the Page Blob Clear Pages operation. + * @returns Response data for the Page Blob Clear Pages operation. + */ + async clearPages(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-clearPages", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.clearPages(0, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + sequenceNumberAccessConditions: options.conditions, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns the list of valid page ranges for a page blob or snapshot of a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns Response data for the Page Blob Get Ranges operation. + */ + async getPageRanges(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-getPageRanges", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this.pageBlobContext.getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + })); + return rangeResponseFromModel(response); + }); + } + /** + * getPageRangesSegment returns a single segment of page ranges starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call getPageRangesSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to PageBlob Get Page Ranges Segment operation. + */ + async listPageRangesSegment(offset = 0, count, marker2, options = {}) { + return tracingClient.withSpan("PageBlobClient-getPageRangesSegment", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + marker: marker2, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesResponseModel} + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param marker - A string value that identifies the portion of + * the get of page ranges to be returned with the next getting operation. The + * operation returns the ContinuationToken value within the response body if the + * getting operation did not return all page ranges remaining within the current page. + * The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of get + * items. The marker value is opaque to the client. + * @param options - Options to List Page Ranges operation. + */ + listPageRangeItemSegments() { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeItemSegments_1(offset = 0, count, marker2, options = {}) { + let getPageRangeItemSegmentsResponse; + if (!!marker2 || marker2 === void 0) { + do { + getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesSegment(offset, count, marker2, options)); + marker2 = getPageRangeItemSegmentsResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to List Page Ranges operation. + */ + listPageRangeItems() { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeItems_1(offset = 0, count, options = {}) { + var _a, e_1, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeItemSegments(offset, count, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const getPageRangesSegment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_1) throw e_1.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list of page ranges for a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * .byPage() returns an async iterable iterator to list of page ranges for a page blob. + * + * Example using `for await` syntax: + * + * ```js + * // Get the pageBlobClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` + * let i = 1; + * for await (const pageRange of pageBlobClient.listPageRanges()) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = pageBlobClient.listPageRanges(); + * let pageRangeItem = await iter.next(); + * while (!pageRangeItem.done) { + * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); + * pageRangeItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of pageBlobClient.listPageRanges().byPage({ maxPageSize: 20 })) { + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = pageBlobClient.listPageRanges().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 page ranges + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = pageBlobClient.listPageRanges().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 page ranges + * for (const blob of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns An asyncIterableIterator that supports paging. + */ + listPageRanges(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + const iter = this.listPageRangeItems(offset, count, options); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listPageRangeItemSegments(offset, count, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); + } + }; + } + /** + * Gets the collection of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page blob + * @param count - Number of bytes to get ranges diff. + * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @returns Response data for the Page Blob Get Page Range Diff operation. + */ + async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-getPageRangesDiff", options, async (updatedOptions) => { + var _a; + const result = assertResponse(await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshot, + range: rangeToString({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + })); + return rangeResponseFromModel(result); + }); + } + /** + * getPageRangesDiffSegment returns a single segment of page ranges starting from the + * specified Marker for difference between previous snapshot and the target page blob. + * Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call getPageRangesDiffSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param marker - A string value that identifies the portion of the get to be returned with the next get operation. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + async listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options = {}) { + return tracingClient.withSpan("PageBlobClient-getPageRangesDiffSegment", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, + leaseAccessConditions: options === null || options === void 0 ? void 0 : options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.conditions), { ifTags: (_a = options === null || options === void 0 ? void 0 : options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshotOrUrl, + range: rangeToString({ + offset, + count + }), + marker: marker2, + maxPageSize: options === null || options === void 0 ? void 0 : options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesDiffResponseModel} + * + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param marker - A string value that identifies the portion of + * the get of page ranges to be returned with the next getting operation. The + * operation returns the ContinuationToken value within the response body if the + * getting operation did not return all page ranges remaining within the current page. + * The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of get + * items. The marker value is opaque to the client. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options) { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItemSegments_1() { + let getPageRangeItemSegmentsResponse; + if (!!marker2 || marker2 === void 0) { + do { + getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options)); + marker2 = getPageRangeItemSegmentsResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + listPageRangeDiffItems(offset, count, prevSnapshotOrUrl, options) { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItems_1() { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const getPageRangesSegment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * .byPage() returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. + * + * Example using `for await` syntax: + * + * ```js + * // Get the pageBlobClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` + * let i = 1; + * for await (const pageRange of pageBlobClient.listPageRangesDiff()) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = pageBlobClient.listPageRangesDiff(); + * let pageRangeItem = await iter.next(); + * while (!pageRangeItem.done) { + * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); + * pageRangeItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 20 })) { + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 page ranges + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = pageBlobClient.listPageRangesDiff().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 page ranges + * for (const blob of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns An asyncIterableIterator that supports paging. + */ + listPageRangesDiff(offset, count, prevSnapshot, options = {}) { + options.conditions = options.conditions || {}; + const iter = this.listPageRangeDiffItems(offset, count, prevSnapshot, Object.assign({}, options)); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listPageRangeDiffItemSegments(offset, count, prevSnapshot, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); + } + }; + } + /** + * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page blob + * @param count - Number of bytes to get ranges diff. + * @param prevSnapshotUrl - URL of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @returns Response data for the Page Blob Get Page Range Diff operation. + */ + async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl2, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevSnapshotUrl: prevSnapshotUrl2, + range: rangeToString({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + })); + return rangeResponseFromModel(response); + }); + } + /** + * Resizes the page blob to the specified size (which must be a multiple of 512). + * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties + * + * @param size - Target size + * @param options - Options to the Page Blob Resize operation. + * @returns Response data for the Page Blob Resize operation. + */ + async resize(size, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-resize", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.resize(size, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Sets a page blob's sequence number. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * + * @param sequenceNumberAction - Indicates how the service should modify the blob's sequence number. + * @param sequenceNumber - Required if sequenceNumberAction is max or update + * @param options - Options to the Page Blob Update Sequence Number operation. + * @returns Response data for the Page Blob Update Sequence Number operation. + */ + async updateSequenceNumber(sequenceNumberAction2, sequenceNumber, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-updateSequenceNumber", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction2, { + abortSignal: options.abortSignal, + blobSequenceNumber: sequenceNumber, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. + * The snapshot is copied such that only the differential changes between the previously + * copied snapshot are transferred to the destination. + * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. + * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob + * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots + * + * @param copySource - Specifies the name of the source page blob snapshot. For example, + * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param options - Options to the Page Blob Copy Incremental operation. + * @returns Response data for the Page Blob Copy Incremental operation. + */ + async startCopyIncremental(copySource2, options = {}) { + return tracingClient.withSpan("PageBlobClient-startCopyIncremental", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.copyIncremental(copySource2, { + abortSignal: options.abortSignal, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + }; + async function getBodyAsText(batchResponse) { + let buffer2 = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); + const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer2); + buffer2 = buffer2.slice(0, responseLength); + return buffer2.toString(); + } + function utf8ByteLength(str2) { + return Buffer.byteLength(str2); + } + var HTTP_HEADER_DELIMITER = ": "; + var SPACE_DELIMITER = " "; + var NOT_FOUND = -1; + var BatchResponseParser = class { + constructor(batchResponse, subRequests) { + if (!batchResponse || !batchResponse.contentType) { + throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); + } + if (!subRequests || subRequests.size === 0) { + throw new RangeError("Invalid state: subRequests is not provided or size is 0."); + } + this.batchResponse = batchResponse; + this.subRequests = subRequests; + this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; + this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`; + this.batchResponseEnding = `--${this.responseBatchBoundary}--`; + } + // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response + async parseBatchResponse() { + if (this.batchResponse._response.status !== HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); + } + const responseBodyAsText = await getBodyAsText(this.batchResponse); + const subResponses = responseBodyAsText.split(this.batchResponseEnding)[0].split(this.perResponsePrefix).slice(1); + const subResponseCount = subResponses.length; + if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { + throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); + } + const deserializedSubResponses = new Array(subResponseCount); + let subResponsesSucceededCount = 0; + let subResponsesFailedCount = 0; + for (let index = 0; index < subResponseCount; index++) { + const subResponse = subResponses[index]; + const deserializedSubResponse = {}; + deserializedSubResponse.headers = coreHttpCompat.toHttpHeadersLike(coreRestPipeline.createHttpHeaders()); + const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); + let subRespHeaderStartFound = false; + let subRespHeaderEndFound = false; + let subRespFailed = false; + let contentId = NOT_FOUND; + for (const responseLine of responseLines) { + if (!subRespHeaderStartFound) { + if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { + contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); + } + if (responseLine.startsWith(HTTP_VERSION_1_1)) { + subRespHeaderStartFound = true; + const tokens = responseLine.split(SPACE_DELIMITER); + deserializedSubResponse.status = parseInt(tokens[1]); + deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); + } + continue; + } + if (responseLine.trim() === "") { + if (!subRespHeaderEndFound) { + subRespHeaderEndFound = true; + } + continue; + } + if (!subRespHeaderEndFound) { + if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { + throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); + } + const tokens = responseLine.split(HTTP_HEADER_DELIMITER); + deserializedSubResponse.headers.set(tokens[0], tokens[1]); + if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { + deserializedSubResponse.errorCode = tokens[1]; + subRespFailed = true; + } + } else { + if (!deserializedSubResponse.bodyAsText) { + deserializedSubResponse.bodyAsText = ""; + } + deserializedSubResponse.bodyAsText += responseLine; + } + } + if (contentId !== NOT_FOUND && Number.isInteger(contentId) && contentId >= 0 && contentId < this.subRequests.size && deserializedSubResponses[contentId] === void 0) { + deserializedSubResponse._request = this.subRequests.get(contentId); + deserializedSubResponses[contentId] = deserializedSubResponse; + } else { + logger.error(`subResponses[${index}] is dropped as the Content-ID is not found or invalid, Content-ID: ${contentId}`); + } + if (subRespFailed) { + subResponsesFailedCount++; + } else { + subResponsesSucceededCount++; + } + } + return { + subResponses: deserializedSubResponses, + subResponsesSucceededCount, + subResponsesFailedCount + }; + } + }; + var MutexLockStatus; + (function(MutexLockStatus2) { + MutexLockStatus2[MutexLockStatus2["LOCKED"] = 0] = "LOCKED"; + MutexLockStatus2[MutexLockStatus2["UNLOCKED"] = 1] = "UNLOCKED"; + })(MutexLockStatus || (MutexLockStatus = {})); + var Mutex = class { + /** + * Lock for a specific key. If the lock has been acquired by another customer, then + * will wait until getting the lock. + * + * @param key - lock key + */ + static async lock(key) { + return new Promise((resolve2) => { + if (this.keys[key] === void 0 || this.keys[key] === MutexLockStatus.UNLOCKED) { + this.keys[key] = MutexLockStatus.LOCKED; + resolve2(); + } else { + this.onUnlockEvent(key, () => { + this.keys[key] = MutexLockStatus.LOCKED; + resolve2(); + }); + } + }); + } + /** + * Unlock a key. + * + * @param key - + */ + static async unlock(key) { + return new Promise((resolve2) => { + if (this.keys[key] === MutexLockStatus.LOCKED) { + this.emitUnlockEvent(key); + } + delete this.keys[key]; + resolve2(); + }); + } + static onUnlockEvent(key, handler) { + if (this.listeners[key] === void 0) { + this.listeners[key] = [handler]; + } else { + this.listeners[key].push(handler); + } + } + static emitUnlockEvent(key) { + if (this.listeners[key] !== void 0 && this.listeners[key].length > 0) { + const handler = this.listeners[key].shift(); + setImmediate(() => { + handler.call(this); + }); + } + } + }; + Mutex.keys = {}; + Mutex.listeners = {}; + var BlobBatch = class { + constructor() { + this.batch = "batch"; + this.batchRequest = new InnerBatchRequest(); + } + /** + * Get the value of Content-Type for a batch request. + * The value must be multipart/mixed with a batch boundary. + * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 + */ + getMultiPartContentType() { + return this.batchRequest.getMultipartContentType(); + } + /** + * Get assembled HTTP request body for sub requests. + */ + getHttpRequestBody() { + return this.batchRequest.getHttpRequestBody(); + } + /** + * Get sub requests that are added into the batch request. + */ + getSubRequests() { + return this.batchRequest.getSubRequests(); + } + async addSubRequestInternal(subRequest, assembleSubRequestFunc) { + await Mutex.lock(this.batch); + try { + this.batchRequest.preAddSubRequest(subRequest); + await assembleSubRequestFunc(); + this.batchRequest.postAddSubRequest(subRequest); + } finally { + await Mutex.unlock(this.batch); + } + } + setBatchType(batchType) { + if (!this.batchType) { + this.batchType = batchType; + } + if (this.batchType !== batchType) { + throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); + } + } + async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { + let url2; + let credential; + if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrOptions instanceof StorageSharedKeyCredential || credentialOrOptions instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrOptions))) { + url2 = urlOrBlobClient; + credential = credentialOrOptions; + } else if (urlOrBlobClient instanceof BlobClient) { + url2 = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + options = credentialOrOptions; + } else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + return tracingClient.withSpan("BatchDeleteRequest-addSubRequest", options, async (updatedOptions) => { + this.setBatchType("delete"); + await this.addSubRequestInternal({ + url: url2, + credential + }, async () => { + await new BlobClient(url2, this.batchRequest.createPipeline(credential)).delete(updatedOptions); + }); + }); + } + async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { + let url2; + let credential; + let tier2; + if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrTier instanceof StorageSharedKeyCredential || credentialOrTier instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrTier))) { + url2 = urlOrBlobClient; + credential = credentialOrTier; + tier2 = tierOrOptions; + } else if (urlOrBlobClient instanceof BlobClient) { + url2 = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + tier2 = credentialOrTier; + options = tierOrOptions; + } else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + return tracingClient.withSpan("BatchSetTierRequest-addSubRequest", options, async (updatedOptions) => { + this.setBatchType("setAccessTier"); + await this.addSubRequestInternal({ + url: url2, + credential + }, async () => { + await new BlobClient(url2, this.batchRequest.createPipeline(credential)).setAccessTier(tier2, updatedOptions); + }); + }); + } + }; + var InnerBatchRequest = class { + constructor() { + this.operationCount = 0; + this.body = ""; + const tempGuid = coreUtil.randomUUID(); + this.boundary = `batch_${tempGuid}`; + this.subRequestPrefix = `--${this.boundary}${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TYPE}: application/http${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; + this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; + this.batchRequestEnding = `--${this.boundary}--`; + this.subRequests = /* @__PURE__ */ new Map(); + } + /** + * Create pipeline to assemble sub requests. The idea here is to use existing + * credential and serialization/deserialization components, with additional policies to + * filter unnecessary headers, assemble sub requests into request's body + * and intercept request from going to wire. + * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + */ + createPipeline(credential) { + const corePipeline = coreRestPipeline.createEmptyPipeline(); + corePipeline.addPolicy(coreClient.serializationPolicy({ + stringifyXML: coreXml.stringifyXML, + serializerOptions: { + xml: { + xmlCharKey: "#" + } + } + }), { phase: "Serialize" }); + corePipeline.addPolicy(batchHeaderFilterPolicy()); + corePipeline.addPolicy(batchRequestAssemblePolicy(this), { afterPhase: "Sign" }); + if (coreAuth.isTokenCredential(credential)) { + corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ + credential, + scopes: StorageOAuthScopes, + challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge } + }), { phase: "Sign" }); + } else if (credential instanceof StorageSharedKeyCredential) { + corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ + accountName: credential.accountName, + accountKey: credential.accountKey + }), { phase: "Sign" }); + } + const pipeline = new Pipeline([]); + pipeline._credential = credential; + pipeline._corePipeline = corePipeline; + return pipeline; + } + appendSubRequestToBody(request) { + this.body += [ + this.subRequestPrefix, + // sub request constant prefix + `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, + // sub request's content ID + "", + // empty line after sub request's content ID + `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}` + // sub request start line with method + ].join(HTTP_LINE_ENDING); + for (const [name, value] of request.headers) { + this.body += `${name}: ${value}${HTTP_LINE_ENDING}`; + } + this.body += HTTP_LINE_ENDING; + } + preAddSubRequest(subRequest) { + if (this.operationCount >= BATCH_MAX_REQUEST) { + throw new RangeError(`Cannot exceed ${BATCH_MAX_REQUEST} sub requests in a single batch`); + } + const path2 = getURLPath(subRequest.url); + if (!path2 || path2 === "") { + throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); + } + } + postAddSubRequest(subRequest) { + this.subRequests.set(this.operationCount, subRequest); + this.operationCount++; + } + // Return the http request body with assembling the ending line to the sub request body. + getHttpRequestBody() { + return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; + } + getMultipartContentType() { + return this.multipartContentType; + } + getSubRequests() { + return this.subRequests; + } + }; + function batchRequestAssemblePolicy(batchRequest) { + return { + name: "batchRequestAssemblePolicy", + async sendRequest(request) { + batchRequest.appendSubRequestToBody(request); + return { + request, + status: 200, + headers: coreRestPipeline.createHttpHeaders() + }; + } + }; + } + function batchHeaderFilterPolicy() { + return { + name: "batchHeaderFilterPolicy", + async sendRequest(request, next) { + let xMsHeaderName = ""; + for (const [name] of request.headers) { + if (iEqual(name, HeaderConstants.X_MS_VERSION)) { + xMsHeaderName = name; + } + } + if (xMsHeaderName !== "") { + request.headers.delete(xMsHeaderName); + } + return next(request); + } + }; + } + var BlobBatchClient = class { + constructor(url2, credentialOrPipeline, options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { + pipeline = credentialOrPipeline; + } else if (!credentialOrPipeline) { + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + pipeline = newPipeline(credentialOrPipeline, options); + } + const storageClientContext = new StorageContextClient(url2, getCoreClientOptions(pipeline)); + const path2 = getURLPath(url2); + if (path2 && path2 !== "/") { + this.serviceOrContainerContext = storageClientContext.container; + } else { + this.serviceOrContainerContext = storageClientContext.service; + } + } + /** + * Creates a {@link BlobBatch}. + * A BlobBatch represents an aggregated set of operations on blobs. + */ + createBatch() { + return new BlobBatch(); + } + async deleteBlobs(urlsOrBlobClients, credentialOrOptions, options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); + } else { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); + } + } + return this.submitBatch(batch); + } + async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); + } else { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); + } + } + return this.submitBatch(batch); + } + /** + * Submit batch request which consists of multiple subrequests. + * + * Get `blobBatchClient` and other details before running the snippets. + * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` + * + * Example usage: + * + * ```js + * let batchRequest = new BlobBatch(); + * await batchRequest.deleteBlob(urlInString0, credential0); + * await batchRequest.deleteBlob(urlInString1, credential1, { + * deleteSnapshots: "include" + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); + * ``` + * + * Example using a lease: + * + * ```js + * let batchRequest = new BlobBatch(); + * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); + * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { + * conditions: { leaseId: leaseId } + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); + * ``` + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @param batchRequest - A set of Delete or SetTier operations. + * @param options - + */ + async submitBatch(batchRequest, options = {}) { + if (!batchRequest || batchRequest.getSubRequests().size === 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + return tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => { + const batchRequestBody = batchRequest.getHttpRequestBody(); + const rawBatchResponse = assertResponse(await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign({}, updatedOptions))); + const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + const responseSummary = await batchResponseParser.parseBatchResponse(); + const res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount + }; + return res; + }); + } + }; + var ContainerClient = class extends StorageClient { + /** + * The name of the container. + */ + get containerName() { + return this._containerName; + } + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { + let pipeline; + let url2; + options = options || {}; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { + url2 = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { + const containerName = credentialOrPipelineOrContainerName; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url2 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + pipeline = newPipeline(sharedKeyCredential, options); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + url2 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } else { + throw new Error("Expecting non-empty strings for containerName parameter"); + } + super(url2, pipeline); + this._containerName = this.getContainerNameFromUrl(); + this.containerContext = this.storageClientContext.container; + } + /** + * Creates a new container under the specified account. If the container with + * the same name already exists, the operation fails. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata + * + * @param options - Options to Container Create operation. + * + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * const createContainerResponse = await containerClient.create(); + * console.log("Container was created successfully", createContainerResponse.requestId); + * ``` + */ + async create(options = {}) { + return tracingClient.withSpan("ContainerClient-create", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.create(updatedOptions)); + }); + } + /** + * Creates a new container under the specified account. If the container with + * the same name already exists, it is not changed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata + * + * @param options - + */ + async createIfNotExists(options = {}) { + return tracingClient.withSpan("ContainerClient-createIfNotExists", options, async (updatedOptions) => { + var _a, _b; + try { + const res = await this.create(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } else { + throw e; + } + } + }); + } + /** + * Returns true if the Azure container resource represented by this client exists; false otherwise. + * + * NOTE: use this function with care since an existing container might be deleted by other clients or + * applications. Vice versa new containers with the same name might be added by other clients or + * applications after this function completes. + * + * @param options - + */ + async exists(options = {}) { + return tracingClient.withSpan("ContainerClient-exists", options, async (updatedOptions) => { + try { + await this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }); + return true; + } catch (e) { + if (e.statusCode === 404) { + return false; + } + throw e; + } + }); + } + /** + * Creates a {@link BlobClient} + * + * @param blobName - A blob name + * @returns A new BlobClient object for the given blob name. + */ + getBlobClient(blobName) { + return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates an {@link AppendBlobClient} + * + * @param blobName - An append blob name + */ + getAppendBlobClient(blobName) { + return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates a {@link BlockBlobClient} + * + * @param blobName - A block blob name + * + * + * Example usage: + * + * ```js + * const content = "Hello world!"; + * + * const blockBlobClient = containerClient.getBlockBlobClient(""); + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); + * ``` + */ + getBlockBlobClient(blobName) { + return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates a {@link PageBlobClient} + * + * @param blobName - A page blob name + */ + getPageBlobClient(blobName) { + return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Returns all user-defined metadata and system properties for the specified + * container. The data returned does not include the container's list of blobs. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties + * + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which + * will retain their original casing. + * + * @param options - Options to Container Get Properties operation. + */ + async getProperties(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-getProperties", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), { tracingOptions: updatedOptions.tracingOptions }))); + }); + } + /** + * Marks the specified container for deletion. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * + * @param options - Options to Container Delete operation. + */ + async delete(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-delete", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.delete({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Marks the specified container for deletion if it exists. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * + * @param options - Options to Container Delete operation. + */ + async deleteIfExists(options = {}) { + return tracingClient.withSpan("ContainerClient-deleteIfExists", options, async (updatedOptions) => { + var _a, _b; + try { + const res = await this.delete(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + throw e; + } + }); + } + /** + * Sets one or more user-defined name-value pairs for the specified container. + * + * If no option provided, or no metadata defined in the parameter, the container + * metadata will be removed. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * + * @param metadata - Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param options - Options to Container Set Metadata operation. + */ + async setMetadata(metadata2, options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + if (options.conditions.ifUnmodifiedSince) { + throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + } + return tracingClient.withSpan("ContainerClient-setMetadata", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.setMetadata({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: metadata2, + modifiedAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Gets the permissions for the specified container. The permissions indicate + * whether container data may be accessed publicly. + * + * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. + * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl + * + * @param options - Options to Container Get Access Policy operation. + */ + async getAccessPolicy(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-getAccessPolicy", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.getAccessPolicy({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + })); + const res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (const identifier of response) { + let accessPolicy = void 0; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); + } + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); + } + } + res.signedIdentifiers.push({ + accessPolicy, + id: identifier.id + }); + } + return res; + }); + } + /** + * Sets the permissions for the specified container. The permissions indicate + * whether blobs in a container may be accessed publicly. + * + * When you set permissions for a container, the existing permissions are replaced. + * If no access or containerAcl provided, the existing container ACL will be + * removed. + * + * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. + * During this interval, a shared access signature that is associated with the stored access policy will + * fail with status code 403 (Forbidden), until the access policy becomes active. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl + * + * @param access - The level of public access to data in the container. + * @param containerAcl - Array of elements each having a unique Id and details of the access policy. + * @param options - Options to Container Set Access Policy operation. + */ + async setAccessPolicy(access3, containerAcl2, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("ContainerClient-setAccessPolicy", options, async (updatedOptions) => { + const acl = []; + for (const identifier of containerAcl2 || []) { + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn ? truncatedISO8061Date(identifier.accessPolicy.startsOn) : "" + }, + id: identifier.id + }); + } + return assertResponse(await this.containerContext.setAccessPolicy({ + abortSignal: options.abortSignal, + access: access3, + containerAcl: acl, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Get a {@link BlobLeaseClient} that manages leases on the container. + * + * @param proposeLeaseId - Initial proposed lease Id. + * @returns A new BlobLeaseClient object for managing leases on the container. + */ + getBlobLeaseClient(proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); + } + /** + * Creates a new block blob, or updates the content of an existing block blob. + * + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. + * + * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, + * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better + * performance with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param blobName - Name of the block blob to create or update. + * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param options - Options to configure the Block Blob Upload operation. + * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. + */ + async uploadBlockBlob(blobName, body2, contentLength2, options = {}) { + return tracingClient.withSpan("ContainerClient-uploadBlockBlob", options, async (updatedOptions) => { + const blockBlobClient = this.getBlockBlobClient(blobName); + const response = await blockBlobClient.upload(body2, contentLength2, updatedOptions); + return { + blockBlobClient, + response + }; + }); + } + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param blobName - + * @param options - Options to Blob Delete operation. + * @returns Block blob deletion response data. + */ + async deleteBlob(blobName, options = {}) { + return tracingClient.withSpan("ContainerClient-deleteBlob", options, async (updatedOptions) => { + let blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); + } + return blobClient.delete(updatedOptions); + }); + } + /** + * listBlobFlatSegment returns a single segment of blobs starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call listBlobsFlatSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to Container List Blob Flat Segment operation. + */ + async listBlobFlatSegment(marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-listBlobFlatSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobFlat(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { + const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return wrappedResponse; + }); + } + /** + * listBlobHierarchySegment returns a single segment of blobs starting from + * the specified Marker. Use an empty Marker to start enumeration from the + * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment + * again (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to Container List Blob Hierarchy Segment operation. + */ + async listBlobHierarchySegment(delimiter2, marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-listBlobHierarchySegment", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this.containerContext.listBlobHierarchySegment(delimiter2, Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobHierarchy(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { + const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); + return blobItem; + }), blobPrefixes: (_a = response.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { + const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); + return blobPrefix; + }) }) }); + return wrappedResponse; + }); + } + /** + * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list blobs operation. + */ + listSegments(marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { + let listBlobsFlatSegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker2, options)); + marker2 = listBlobsFlatSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator of {@link BlobItem} objects + * + * @param options - Options to list blobs operation. + */ + listItems() { + return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { + var _a, e_1, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const listBlobsFlatSegmentResponse = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_1) throw e_1.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list all the blobs + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * Example using `for await` syntax: + * + * ```js + * // Get the containerClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("");` + * let i = 1; + * for await (const blob of containerClient.listBlobsFlat()) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = containerClient.listBlobsFlat(); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * @param options - Options to list blobs. + * @returns An asyncIterableIterator that supports paging. + */ + listBlobsFlat(options = {}) { + const include2 = []; + if (options.includeCopy) { + include2.push("copy"); + } + if (options.includeDeleted) { + include2.push("deleted"); + } + if (options.includeMetadata) { + include2.push("metadata"); + } + if (options.includeSnapshots) { + include2.push("snapshots"); + } + if (options.includeVersions) { + include2.push("versions"); + } + if (options.includeUncommitedBlobs) { + include2.push("uncommittedblobs"); + } + if (options.includeTags) { + include2.push("tags"); + } + if (options.includeDeletedWithVersions) { + include2.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include2.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include2.push("legalhold"); + } + if (options.prefix === "") { + options.prefix = void 0; + } + const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItems(updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; + } + /** + * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list blobs operation. + */ + listHierarchySegments(delimiter_1, marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1(delimiter2, marker2, options = {}) { + let listBlobsHierarchySegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter2, marker2, options)); + marker2 = listBlobsHierarchySegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param options - Options to list blobs operation. + */ + listItemsByHierarchy(delimiter_1) { + return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1(delimiter2, options = {}) { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listHierarchySegments(delimiter2, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const listBlobsHierarchySegmentResponse = _c; + const segment = listBlobsHierarchySegmentResponse.segment; + if (segment.blobPrefixes) { + for (const prefix2 of segment.blobPrefixes) { + yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix2)); + } + } + for (const blob of segment.blobItems) { + yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); + } + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list all the blobs by hierarchy. + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. + * + * Example using `for await` syntax: + * + * ```js + * for await (const item of containerClient.listBlobsByHierarchy("/")) { + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}`); + * } + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); + * let entity = await iter.next(); + * while (!entity.done) { + * let item = entity.value; + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}`); + * } + * entity = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * console.log("Listing blobs by hierarchy by page"); + * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { + * const segment = response.segment; + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a max page size: + * + * ```js + * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); + * + * let i = 1; + * for await (const response of containerClient + * .listBlobsByHierarchy("/", { prefix: "prefix2/sub1/" }) + * .byPage({ maxPageSize: 2 })) { + * console.log(`Page ${i++}`); + * const segment = response.segment; + * + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}`); + * } + * } + * ``` + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param options - Options to list blobs operation. + */ + listBlobsByHierarchy(delimiter2, options = {}) { + if (delimiter2 === "") { + throw new RangeError("delimiter should contain one or more characters"); + } + const include2 = []; + if (options.includeCopy) { + include2.push("copy"); + } + if (options.includeDeleted) { + include2.push("deleted"); + } + if (options.includeMetadata) { + include2.push("metadata"); + } + if (options.includeSnapshots) { + include2.push("snapshots"); + } + if (options.includeVersions) { + include2.push("versions"); + } + if (options.includeUncommitedBlobs) { + include2.push("uncommittedblobs"); + } + if (options.includeTags) { + include2.push("tags"); + } + if (options.includeDeletedWithVersions) { + include2.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include2.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include2.push("legalhold"); + } + if (options.prefix === "") { + options.prefix = void 0; + } + const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItemsByHierarchy(delimiter2, updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + async next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listHierarchySegments(delimiter2, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; + } + /** + * The Filter Blobs operation enables callers to list blobs in the container whose tags + * match a given search expression. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to find blobs by tags. + */ + async findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-findBlobsByTagsSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker2, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { + var _a; + let tagValue = ""; + if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); + }) }); + return wrappedResponse; + }); + } + /** + * Returns an AsyncIterableIterator for ContainerFindBlobsByTagsSegmentResponse. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to find blobs by tags. + */ + findBlobsByTagsSegments(tagFilterSqlExpression_1, marker_1) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1(tagFilterSqlExpression, marker2, options = {}) { + let response; + if (!!marker2 || marker2 === void 0) { + do { + response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options)); + response.blobs = response.blobs || []; + marker2 = response.continuationToken; + yield yield tslib.__await(response); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator for blobs. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param options - Options to findBlobsByTagsItems. + */ + findBlobsByTagsItems(tagFilterSqlExpression_1) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { + var _a, e_3, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const segment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_3) throw e_3.error; + } + } + }); + } + /** + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified container. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const blob of containerClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = containerClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = containerClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param options - Options to find blobs by tags. + */ + findBlobsByTags(tagFilterSqlExpression, options = {}) { + const listSegmentOptions = Object.assign({}, options); + const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } + /** + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * + * @param options - Options to the Service Get Account Info operation. + * @returns Response data for the Service Get Account Info operation. + */ + async getAccountInfo(options = {}) { + return tracingClient.withSpan("ContainerClient-getAccountInfo", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + getContainerNameFromUrl() { + let containerName; + try { + const parsedUrl = new URL(this.url); + if (parsedUrl.hostname.split(".")[1] === "blob") { + containerName = parsedUrl.pathname.split("/")[1]; + } else if (isIpEndpointStyle(parsedUrl)) { + containerName = parsedUrl.pathname.split("/")[2]; + } else { + containerName = parsedUrl.pathname.split("/")[1]; + } + containerName = decodeURIComponent(containerName); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return containerName; + } catch (error2) { + throw new Error("Unable to extract containerName with provided information."); + } + } + /** + * Only available for ContainerClient constructed with a shared key credential. + * + * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateSasUrl(options) { + return new Promise((resolve2) => { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); + resolve2(appendToURLQuery(this.url, sas)); + }); + } + /** + * Only available for ContainerClient constructed with a shared key credential. + * + * Generates string to sign for a Blob Container Service Shared Access Signature (SAS) URI + * based on the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + generateSasStringToSign(options) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName }, options), this.credential).stringToSign; + } + /** + * Creates a BlobBatchClient object to conduct batch operations. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns A new BlobBatchClient object for this container. + */ + getBlobBatchClient() { + return new BlobBatchClient(this.url, this.pipeline); + } + }; + var AccountSASPermissions = class _AccountSASPermissions { + constructor() { + this.read = false; + this.write = false; + this.delete = false; + this.deleteVersion = false; + this.list = false; + this.add = false; + this.create = false; + this.update = false; + this.process = false; + this.tag = false; + this.filter = false; + this.setImmutabilityPolicy = false; + this.permanentDelete = false; + } + /** + * Parse initializes the AccountSASPermissions fields from a string. + * + * @param permissions - + */ + static parse(permissions) { + const accountSASPermissions = new _AccountSASPermissions(); + for (const c of permissions) { + switch (c) { + case "r": + accountSASPermissions.read = true; + break; + case "w": + accountSASPermissions.write = true; + break; + case "d": + accountSASPermissions.delete = true; + break; + case "x": + accountSASPermissions.deleteVersion = true; + break; + case "l": + accountSASPermissions.list = true; + break; + case "a": + accountSASPermissions.add = true; + break; + case "c": + accountSASPermissions.create = true; + break; + case "u": + accountSASPermissions.update = true; + break; + case "p": + accountSASPermissions.process = true; + break; + case "t": + accountSASPermissions.tag = true; + break; + case "f": + accountSASPermissions.filter = true; + break; + case "i": + accountSASPermissions.setImmutabilityPolicy = true; + break; + case "y": + accountSASPermissions.permanentDelete = true; + break; + default: + throw new RangeError(`Invalid permission character: ${c}`); + } + } + return accountSASPermissions; + } + /** + * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. + * + * @param permissionLike - + */ + static from(permissionLike) { + const accountSASPermissions = new _AccountSASPermissions(); + if (permissionLike.read) { + accountSASPermissions.read = true; + } + if (permissionLike.write) { + accountSASPermissions.write = true; + } + if (permissionLike.delete) { + accountSASPermissions.delete = true; + } + if (permissionLike.deleteVersion) { + accountSASPermissions.deleteVersion = true; + } + if (permissionLike.filter) { + accountSASPermissions.filter = true; + } + if (permissionLike.tag) { + accountSASPermissions.tag = true; + } + if (permissionLike.list) { + accountSASPermissions.list = true; + } + if (permissionLike.add) { + accountSASPermissions.add = true; + } + if (permissionLike.create) { + accountSASPermissions.create = true; + } + if (permissionLike.update) { + accountSASPermissions.update = true; + } + if (permissionLike.process) { + accountSASPermissions.process = true; + } + if (permissionLike.setImmutabilityPolicy) { + accountSASPermissions.setImmutabilityPolicy = true; + } + if (permissionLike.permanentDelete) { + accountSASPermissions.permanentDelete = true; + } + return accountSASPermissions; + } + /** + * Produces the SAS permissions string for an Azure Storage account. + * Call this method to set AccountSASSignatureValues Permissions field. + * + * Using this method will guarantee the resource types are in + * an order accepted by the service. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + */ + toString() { + const permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.filter) { + permissions.push("f"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.list) { + permissions.push("l"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.update) { + permissions.push("u"); + } + if (this.process) { + permissions.push("p"); + } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } + if (this.permanentDelete) { + permissions.push("y"); + } + return permissions.join(""); + } + }; + var AccountSASResourceTypes = class _AccountSASResourceTypes { + constructor() { + this.service = false; + this.container = false; + this.object = false; + } + /** + * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an + * Error if it encounters a character that does not correspond to a valid resource type. + * + * @param resourceTypes - + */ + static parse(resourceTypes) { + const accountSASResourceTypes = new _AccountSASResourceTypes(); + for (const c of resourceTypes) { + switch (c) { + case "s": + accountSASResourceTypes.service = true; + break; + case "c": + accountSASResourceTypes.container = true; + break; + case "o": + accountSASResourceTypes.object = true; + break; + default: + throw new RangeError(`Invalid resource type: ${c}`); + } + } + return accountSASResourceTypes; + } + /** + * Converts the given resource types to a string. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + */ + toString() { + const resourceTypes = []; + if (this.service) { + resourceTypes.push("s"); + } + if (this.container) { + resourceTypes.push("c"); + } + if (this.object) { + resourceTypes.push("o"); + } + return resourceTypes.join(""); + } + }; + var AccountSASServices = class _AccountSASServices { + constructor() { + this.blob = false; + this.file = false; + this.queue = false; + this.table = false; + } + /** + * Creates an {@link AccountSASServices} from the specified services string. This method will throw an + * Error if it encounters a character that does not correspond to a valid service. + * + * @param services - + */ + static parse(services) { + const accountSASServices = new _AccountSASServices(); + for (const c of services) { + switch (c) { + case "b": + accountSASServices.blob = true; + break; + case "f": + accountSASServices.file = true; + break; + case "q": + accountSASServices.queue = true; + break; + case "t": + accountSASServices.table = true; + break; + default: + throw new RangeError(`Invalid service character: ${c}`); + } + } + return accountSASServices; + } + /** + * Converts the given services to a string. + * + */ + toString() { + const services = []; + if (this.blob) { + services.push("b"); + } + if (this.table) { + services.push("t"); + } + if (this.queue) { + services.push("q"); + } + if (this.file) { + services.push("f"); + } + return services.join(""); + } + }; + function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential).sasQueryParameters; + } + function generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) { + const version2 = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.setImmutabilityPolicy && version2 < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.permanentDelete && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'y' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.tag && version2 < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.filter && version2 < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); + } + if (accountSASSignatureValues.encryptionScope && version2 < "2020-12-06") { + throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); + } + const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + let stringToSign; + if (version2 >= "2020-12-06") { + stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version2, + accountSASSignatureValues.encryptionScope ? accountSASSignatureValues.encryptionScope : "", + "" + // Account SAS requires an additional newline character + ].join("\n"); + } else { + stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version2, + "" + // Account SAS requires an additional newline character + ].join("\n"); + } + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(version2, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, accountSASSignatureValues.encryptionScope), + stringToSign + }; + } + var BlobServiceClient = class _BlobServiceClient extends StorageClient { + /** + * + * Creates an instance of BlobServiceClient from connection string. + * + * @param connectionString - Account connection string or a SAS connection string of an Azure storage account. + * [ Note - Account connection string can only be used in NODE.JS runtime. ] + * Account connection string example - + * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` + * SAS connection string example - + * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` + * @param options - Optional. Options to configure the HTTP pipeline. + */ + static fromConnectionString(connectionString, options) { + options = options || {}; + const extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + const pipeline = newPipeline(sharedKeyCredential, options); + return new _BlobServiceClient(extractedCreds.url, pipeline); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + const pipeline = newPipeline(new AnonymousCredential(), options); + return new _BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + constructor(url2, credentialOrPipeline, options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { + pipeline = credentialOrPipeline; + } else if (coreUtil.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential || credentialOrPipeline instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipeline)) { + pipeline = newPipeline(credentialOrPipeline, options); + } else { + pipeline = newPipeline(new AnonymousCredential(), options); + } + super(url2, pipeline); + this.serviceContext = this.storageClientContext.service; + } + /** + * Creates a {@link ContainerClient} object + * + * @param containerName - A container name + * @returns A new ContainerClient object for the given container name. + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * ``` + */ + getContainerClient(containerName) { + return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + } + /** + * Create a Blob container. @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * + * @param containerName - Name of the container to create. + * @param options - Options to configure Container Create operation. + * @returns Container creation response and the corresponding container client. + */ + async createContainer(containerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-createContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(containerName); + const containerCreateResponse = await containerClient.create(updatedOptions); + return { + containerClient, + containerCreateResponse + }; + }); + } + /** + * Deletes a Blob container. + * + * @param containerName - Name of the container to delete. + * @param options - Options to configure Container Delete operation. + * @returns Container deletion response. + */ + async deleteContainer(containerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-deleteContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(containerName); + return containerClient.delete(updatedOptions); + }); + } + /** + * Restore a previously deleted Blob container. + * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. + * + * @param deletedContainerName - Name of the previously deleted container. + * @param deletedContainerVersion - Version of the previously deleted container, used to uniquely identify the deleted container. + * @param options - Options to configure Container Restore operation. + * @returns Container deletion response. + */ + async undeleteContainer(deletedContainerName2, deletedContainerVersion2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-undeleteContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName2); + const containerContext = containerClient["storageClientContext"].container; + const containerUndeleteResponse = assertResponse(await containerContext.restore({ + deletedContainerName: deletedContainerName2, + deletedContainerVersion: deletedContainerVersion2, + tracingOptions: updatedOptions.tracingOptions + })); + return { containerClient, containerUndeleteResponse }; + }); + } + /** + * Rename an existing Blob Container. + * + * @param sourceContainerName - The name of the source container. + * @param destinationContainerName - The new name of the container. + * @param options - Options to configure Container Rename operation. + */ + /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ + // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. + async renameContainer(sourceContainerName2, destinationContainerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-renameContainer", options, async (updatedOptions) => { + var _a; + const containerClient = this.getContainerClient(destinationContainerName); + const containerContext = containerClient["storageClientContext"].container; + const containerRenameResponse = assertResponse(await containerContext.rename(sourceContainerName2, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId }))); + return { containerClient, containerRenameResponse }; + }); + } + /** + * Gets the properties of a storage account’s Blob service, including properties + * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * @param options - Options to the Service Get Properties operation. + * @returns Response data for the Service Get Properties operation. + */ + async getProperties(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getProperties", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Sets properties for a storage account’s Blob service endpoint, including properties + * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties + * + * @param properties - + * @param options - Options to the Service Set Properties operation. + * @returns Response data for the Service Set Properties operation. + */ + async setProperties(properties, options = {}) { + return tracingClient.withSpan("BlobServiceClient-setProperties", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Retrieves statistics related to replication for the Blob service. It is only + * available on the secondary location endpoint when read-access geo-redundant + * replication is enabled for the storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats + * + * @param options - Options to the Service Get Statistics operation. + * @returns Response data for the Service Get Statistics operation. + */ + async getStatistics(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getStatistics", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * + * @param options - Options to the Service Get Account Info operation. + * @returns Response data for the Service Get Account Info operation. + */ + async getAccountInfo(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getAccountInfo", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns a list of the containers under the specified account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 + * + * @param marker - A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to the Service List Container Segment operation. + * @returns Response data for the Service List Container Segment operation. + */ + async listContainersSegment(marker2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-listContainersSegment", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.listContainersSegment(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker: marker2 }, options), { include: typeof options.include === "string" ? [options.include] : options.include, tracingOptions: updatedOptions.tracingOptions }))); + }); + } + /** + * The Filter Blobs operation enables callers to list blobs across all containers whose tags + * match a given search expression. Filter blobs searches across all containers within a + * storage account but can be scoped within the expression to a single container. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to find blobs by tags. + */ + async findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-findBlobsByTagsSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.serviceContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker2, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { + var _a; + let tagValue = ""; + if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); + }) }); + return wrappedResponse; + }); + } + /** + * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to find blobs by tags. + */ + findBlobsByTagsSegments(tagFilterSqlExpression_1, marker_1) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1(tagFilterSqlExpression, marker2, options = {}) { + let response; + if (!!marker2 || marker2 === void 0) { + do { + response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options)); + response.blobs = response.blobs || []; + marker2 = response.continuationToken; + yield yield tslib.__await(response); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator for blobs. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param options - Options to findBlobsByTagsItems. + */ + findBlobsByTagsItems(tagFilterSqlExpression_1) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { + var _a, e_1, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const segment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_1) throw e_1.error; + } + } + }); + } + /** + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param options - Options to find blobs by tags. + */ + findBlobsByTags(tagFilterSqlExpression, options = {}) { + const listSegmentOptions = Object.assign({}, options); + const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } + /** + * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses + * + * @param marker - A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list containers operation. + */ + listSegments(marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { + let listContainersSegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker2, options)); + listContainersSegmentResponse.containerItems = listContainersSegmentResponse.containerItems || []; + marker2 = listContainersSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator for Container Items + * + * @param options - Options to list containers operation. + */ + listItems() { + return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const segment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list all the containers + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the containers in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const container of blobServiceClient.listContainers()) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.listContainers(); + * let containerItem = await iter.next(); + * while (!containerItem.done) { + * console.log(`Container ${i++}: ${containerItem.value.name}`); + * containerItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .listContainers() + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * ``` + * + * @param options - Options to list containers. + * @returns An asyncIterableIterator that supports paging. + */ + listContainers(options = {}) { + if (options.prefix === "") { + options.prefix = void 0; + } + const include2 = []; + if (options.includeDeleted) { + include2.push("deleted"); + } + if (options.includeMetadata) { + include2.push("metadata"); + } + if (options.includeSystem) { + include2.push("system"); + } + const listSegmentOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItems(listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } + /** + * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). + * + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * + * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time + * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time + */ + async getUserDelegationKey(startsOn, expiresOn2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-getUserDelegationKey", options, async (updatedOptions) => { + const response = assertResponse(await this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn2, false) + }, { + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + const userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + value: response.value + }; + const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return res; + }); + } + /** + * Creates a BlobBatchClient object to conduct batch operations. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns A new BlobBatchClient object for this service. + */ + getBlobBatchClient() { + return new BlobBatchClient(this.url, this.pipeline); + } + /** + * Only available for BlobServiceClient constructed with a shared key credential. + * + * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param permissions - Specifies the list of permissions to be associated with the SAS. + * @param resourceTypes - Specifies the resource types associated with the shared access signature. + * @param options - Optional parameters. + * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateAccountSasUrl(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + } + if (expiresOn2 === void 0) { + const now = /* @__PURE__ */ new Date(); + expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + } + const sas = generateAccountSASQueryParameters(Object.assign({ + permissions, + expiresOn: expiresOn2, + resourceTypes, + services: AccountSASServices.parse("b").toString() + }, options), this.credential).toString(); + return appendToURLQuery(this.url, sas); + } + /** + * Only available for BlobServiceClient constructed with a shared key credential. + * + * Generates string to sign for a Blob account Shared Access Signature (SAS) URI based on + * the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param permissions - Specifies the list of permissions to be associated with the SAS. + * @param resourceTypes - Specifies the resource types associated with the shared access signature. + * @param options - Optional parameters. + * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateSasStringToSign(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + } + if (expiresOn2 === void 0) { + const now = /* @__PURE__ */ new Date(); + expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + } + return generateAccountSASQueryParametersInternal(Object.assign({ + permissions, + expiresOn: expiresOn2, + resourceTypes, + services: AccountSASServices.parse("b").toString() + }, options), this.credential).stringToSign; + } + }; + exports2.KnownEncryptionAlgorithmType = void 0; + (function(KnownEncryptionAlgorithmType) { + KnownEncryptionAlgorithmType["AES256"] = "AES256"; + })(exports2.KnownEncryptionAlgorithmType || (exports2.KnownEncryptionAlgorithmType = {})); + Object.defineProperty(exports2, "RestError", { + enumerable: true, + get: function() { + return coreRestPipeline.RestError; + } + }); + exports2.AccountSASPermissions = AccountSASPermissions; + exports2.AccountSASResourceTypes = AccountSASResourceTypes; + exports2.AccountSASServices = AccountSASServices; + exports2.AnonymousCredential = AnonymousCredential; + exports2.AnonymousCredentialPolicy = AnonymousCredentialPolicy; + exports2.AppendBlobClient = AppendBlobClient; + exports2.BaseRequestPolicy = BaseRequestPolicy; + exports2.BlobBatch = BlobBatch; + exports2.BlobBatchClient = BlobBatchClient; + exports2.BlobClient = BlobClient; + exports2.BlobLeaseClient = BlobLeaseClient; + exports2.BlobSASPermissions = BlobSASPermissions; + exports2.BlobServiceClient = BlobServiceClient; + exports2.BlockBlobClient = BlockBlobClient; + exports2.ContainerClient = ContainerClient; + exports2.ContainerSASPermissions = ContainerSASPermissions; + exports2.Credential = Credential2; + exports2.CredentialPolicy = CredentialPolicy; + exports2.PageBlobClient = PageBlobClient; + exports2.Pipeline = Pipeline; + exports2.SASQueryParameters = SASQueryParameters; + exports2.StorageBrowserPolicy = StorageBrowserPolicy; + exports2.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; + exports2.StorageOAuthScopes = StorageOAuthScopes; + exports2.StorageRetryPolicy = StorageRetryPolicy; + exports2.StorageRetryPolicyFactory = StorageRetryPolicyFactory; + exports2.StorageSharedKeyCredential = StorageSharedKeyCredential; + exports2.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; + exports2.generateAccountSASQueryParameters = generateAccountSASQueryParameters; + exports2.generateBlobSASQueryParameters = generateBlobSASQueryParameters; + exports2.getBlobServiceAccountAudience = getBlobServiceAccountAudience; + exports2.isPipelineLike = isPipelineLike; + exports2.logger = logger; + exports2.newPipeline = newPipeline; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/errors.js +var require_errors2 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/errors.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.CacheNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0; + var FilesNotFoundError = class extends Error { + constructor(files = []) { + let message = "No files were found to upload"; + if (files.length > 0) { + message += `: ${files.join(", ")}`; + } + super(message); + this.files = files; + this.name = "FilesNotFoundError"; + } + }; + exports2.FilesNotFoundError = FilesNotFoundError; + var InvalidResponseError = class extends Error { + constructor(message) { + super(message); + this.name = "InvalidResponseError"; + } + }; + exports2.InvalidResponseError = InvalidResponseError; + var CacheNotFoundError = class extends Error { + constructor(message = "Cache not found") { + super(message); + this.name = "CacheNotFoundError"; + } + }; + exports2.CacheNotFoundError = CacheNotFoundError; + var GHESNotSupportedError = class extends Error { + constructor(message = "@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.") { + super(message); + this.name = "GHESNotSupportedError"; + } + }; + exports2.GHESNotSupportedError = GHESNotSupportedError; + var NetworkError = class extends Error { + constructor(code) { + const message = `Unable to make request: ${code} +If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; + super(message); + this.code = code; + this.name = "NetworkError"; + } + }; + exports2.NetworkError = NetworkError; + NetworkError.isNetworkErrorCode = (code) => { + if (!code) + return false; + return [ + "ECONNRESET", + "ENOTFOUND", + "ETIMEDOUT", + "ECONNREFUSED", + "EHOSTUNREACH" + ].includes(code); + }; + var UsageError = class extends Error { + constructor() { + const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours. +More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; + super(message); + this.name = "UsageError"; + } + }; + exports2.UsageError = UsageError; + UsageError.isUsageErrorMessage = (msg) => { + if (!msg) + return false; + return msg.includes("insufficient usage"); + }; + } +}); + +// node_modules/@actions/cache/lib/internal/uploadUtils.js +var require_uploadUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/uploadUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.uploadCacheArchiveSDK = exports2.UploadProgress = void 0; + var core12 = __importStar4(require_core()); + var storage_blob_1 = require_dist7(); + var errors_1 = require_errors2(); + var UploadProgress = class { + constructor(contentLength) { + this.contentLength = contentLength; + this.sentBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); + } + /** + * Sets the number of bytes sent + * + * @param sentBytes the number of bytes sent + */ + setSentBytes(sentBytes) { + this.sentBytes = sentBytes; + } + /** + * Returns the total number of bytes transferred. + */ + getTransferredBytes() { + return this.sentBytes; + } + /** + * Returns true if the upload is complete. + */ + isDone() { + return this.getTransferredBytes() === this.contentLength; + } + /** + * Prints the current upload stats. Once the upload completes, this will print one + * last line and then stop. + */ + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.sentBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); + core12.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; + } + } + /** + * Returns a function used to handle TransferProgressEvents. + */ + onProgress() { + return (progress) => { + this.setSentBytes(progress.loadedBytes); + }; + } + /** + * Starts the timer that displays the stats. + * + * @param delayInMs the delay between each write + */ + startDisplayTimer(delayInMs = 1e3) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + /** + * Stops the timer that displays the stats. As this typically indicates the upload + * is complete, this will display one last line, unless the last line has already + * been written. + */ + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = void 0; + } + this.display(); + } + }; + exports2.UploadProgress = UploadProgress; + function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const blobClient = new storage_blob_1.BlobClient(signedUploadURL); + const blockBlobClient = blobClient.getBlockBlobClient(); + const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0); + const uploadOptions = { + blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize, + concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency, + maxSingleShotSize: 128 * 1024 * 1024, + onProgress: uploadProgress.onProgress() + }; + try { + uploadProgress.startDisplayTimer(); + core12.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); + const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions); + if (response._response.status >= 400) { + throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`); + } + return response; + } catch (error2) { + core12.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error2.message}`); + throw error2; + } finally { + uploadProgress.stopDisplayTimer(); + } + }); + } + exports2.uploadCacheArchiveSDK = uploadCacheArchiveSDK; + } +}); + +// node_modules/@actions/cache/lib/internal/requestUtils.js +var require_requestUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/requestUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; + var core12 = __importStar4(require_core()); + var http_client_1 = require_lib(); + var constants_1 = require_constants7(); + function isSuccessStatusCode(statusCode) { + if (!statusCode) { + return false; + } + return statusCode >= 200 && statusCode < 300; + } + exports2.isSuccessStatusCode = isSuccessStatusCode; + function isServerErrorStatusCode(statusCode) { + if (!statusCode) { + return true; + } + return statusCode >= 500; + } + exports2.isServerErrorStatusCode = isServerErrorStatusCode; + function isRetryableStatusCode(statusCode) { + if (!statusCode) { + return false; + } + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.GatewayTimeout + ]; + return retryableStatusCodes.includes(statusCode); + } + exports2.isRetryableStatusCode = isRetryableStatusCode; + function sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => setTimeout(resolve2, milliseconds)); + }); + } + function retry3(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay, onError = void 0) { + return __awaiter4(this, void 0, void 0, function* () { + let errorMessage = ""; + let attempt = 1; + while (attempt <= maxAttempts) { + let response = void 0; + let statusCode = void 0; + let isRetryable = false; + try { + response = yield method(); + } catch (error2) { + if (onError) { + response = onError(error2); + } + isRetryable = true; + errorMessage = error2.message; + } + if (response) { + statusCode = getStatusCode(response); + if (!isServerErrorStatusCode(statusCode)) { + return response; + } + } + if (statusCode) { + isRetryable = isRetryableStatusCode(statusCode); + errorMessage = `Cache service responded with ${statusCode}`; + } + core12.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + if (!isRetryable) { + core12.debug(`${name} - Error is not retryable`); + break; + } + yield sleep(delay2); + attempt++; + } + throw Error(`${name} failed: ${errorMessage}`); + }); + } + exports2.retry = retry3; + function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay) { + return __awaiter4(this, void 0, void 0, function* () { + return yield retry3( + name, + method, + (response) => response.statusCode, + maxAttempts, + delay2, + // If the error object contains the statusCode property, extract it and return + // an TypedResponse so it can be processed by the retry logic. + (error2) => { + if (error2 instanceof http_client_1.HttpClientError) { + return { + statusCode: error2.statusCode, + result: null, + headers: {}, + error: error2 + }; + } else { + return void 0; + } + } + ); + }); + } + exports2.retryTypedResponse = retryTypedResponse; + function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay) { + return __awaiter4(this, void 0, void 0, function* () { + return yield retry3(name, method, (response) => response.message.statusCode, maxAttempts, delay2); + }); + } + exports2.retryHttpClientResponse = retryHttpClientResponse; + } +}); + +// node_modules/@actions/cache/lib/internal/downloadUtils.js +var require_downloadUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/downloadUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; + var core12 = __importStar4(require_core()); + var http_client_1 = require_lib(); + var storage_blob_1 = require_dist7(); + var buffer = __importStar4(require("buffer")); + var fs = __importStar4(require("fs")); + var stream = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var requestUtils_1 = require_requestUtils(); + var abort_controller_1 = require_dist5(); + function pipeResponseToStream(response, output) { + return __awaiter4(this, void 0, void 0, function* () { + const pipeline = util.promisify(stream.pipeline); + yield pipeline(response.message, output); + }); + } + var DownloadProgress = class { + constructor(contentLength) { + this.contentLength = contentLength; + this.segmentIndex = 0; + this.segmentSize = 0; + this.segmentOffset = 0; + this.receivedBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); + } + /** + * Progress to the next segment. Only call this method when the previous segment + * is complete. + * + * @param segmentSize the length of the next segment + */ + nextSegment(segmentSize) { + this.segmentOffset = this.segmentOffset + this.segmentSize; + this.segmentIndex = this.segmentIndex + 1; + this.segmentSize = segmentSize; + this.receivedBytes = 0; + core12.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); + } + /** + * Sets the number of bytes received for the current segment. + * + * @param receivedBytes the number of bytes received + */ + setReceivedBytes(receivedBytes) { + this.receivedBytes = receivedBytes; + } + /** + * Returns the total number of bytes transferred. + */ + getTransferredBytes() { + return this.segmentOffset + this.receivedBytes; + } + /** + * Returns true if the download is complete. + */ + isDone() { + return this.getTransferredBytes() === this.contentLength; + } + /** + * Prints the current download stats. Once the download completes, this will print one + * last line and then stop. + */ + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.segmentOffset + this.receivedBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const downloadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); + core12.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; + } + } + /** + * Returns a function used to handle TransferProgressEvents. + */ + onProgress() { + return (progress) => { + this.setReceivedBytes(progress.loadedBytes); + }; + } + /** + * Starts the timer that displays the stats. + * + * @param delayInMs the delay between each write + */ + startDisplayTimer(delayInMs = 1e3) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + /** + * Stops the timer that displays the stats. As this typically indicates the download + * is complete, this will display one last line, unless the last line has already + * been written. + */ + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = void 0; + } + this.display(); + } + }; + exports2.DownloadProgress = DownloadProgress; + function downloadCacheHttpClient(archiveLocation, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const writeStream = fs.createWriteStream(archivePath); + const httpClient = new http_client_1.HttpClient("actions/cache"); + const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.get(archiveLocation); + })); + downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { + downloadResponse.message.destroy(); + core12.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); + }); + yield pipeResponseToStream(downloadResponse, writeStream); + const contentLengthHeader = downloadResponse.message.headers["content-length"]; + if (contentLengthHeader) { + const expectedLength = parseInt(contentLengthHeader); + const actualLength = utils.getArchiveFileSizeInBytes(archivePath); + if (actualLength !== expectedLength) { + throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); + } + } else { + core12.debug("Unable to validate download, no Content-Length header"); + } + }); + } + exports2.downloadCacheHttpClient = downloadCacheHttpClient; + function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const archiveDescriptor = yield fs.promises.open(archivePath, "w"); + const httpClient = new http_client_1.HttpClient("actions/cache", void 0, { + socketTimeout: options.timeoutInMs, + keepAlive: true + }); + try { + const res = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCacheMetadata", () => __awaiter4(this, void 0, void 0, function* () { + return yield httpClient.request("HEAD", archiveLocation, null, {}); + })); + const lengthHeader = res.message.headers["content-length"]; + if (lengthHeader === void 0 || lengthHeader === null) { + throw new Error("Content-Length not found on blob response"); + } + const length = parseInt(lengthHeader); + if (Number.isNaN(length)) { + throw new Error(`Could not interpret Content-Length: ${length}`); + } + const downloads = []; + const blockSize = 4 * 1024 * 1024; + for (let offset = 0; offset < length; offset += blockSize) { + const count = Math.min(blockSize, length - offset); + downloads.push({ + offset, + promiseGetter: () => __awaiter4(this, void 0, void 0, function* () { + return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count); + }) + }); + } + downloads.reverse(); + let actives = 0; + let bytesDownloaded = 0; + const progress = new DownloadProgress(length); + progress.startDisplayTimer(); + const progressFn = progress.onProgress(); + const activeDownloads = []; + let nextDownload; + const waitAndWrite = () => __awaiter4(this, void 0, void 0, function* () { + const segment = yield Promise.race(Object.values(activeDownloads)); + yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset); + actives--; + delete activeDownloads[segment.offset]; + bytesDownloaded += segment.count; + progressFn({ loadedBytes: bytesDownloaded }); + }); + while (nextDownload = downloads.pop()) { + activeDownloads[nextDownload.offset] = nextDownload.promiseGetter(); + actives++; + if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) { + yield waitAndWrite(); + } + } + while (actives > 0) { + yield waitAndWrite(); + } + } finally { + httpClient.dispose(); + yield archiveDescriptor.close(); + } + }); + } + exports2.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent; + function downloadSegmentRetry(httpClient, archiveLocation, offset, count) { + return __awaiter4(this, void 0, void 0, function* () { + const retries = 5; + let failures = 0; + while (true) { + try { + const timeout = 3e4; + const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count)); + if (typeof result === "string") { + throw new Error("downloadSegmentRetry failed due to timeout"); + } + return result; + } catch (err) { + if (failures >= retries) { + throw err; + } + failures++; + } + } + }); + } + function downloadSegment(httpClient, archiveLocation, offset, count) { + return __awaiter4(this, void 0, void 0, function* () { + const partRes = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCachePart", () => __awaiter4(this, void 0, void 0, function* () { + return yield httpClient.get(archiveLocation, { + Range: `bytes=${offset}-${offset + count - 1}` + }); + })); + if (!partRes.readBodyBuffer) { + throw new Error("Expected HttpClientResponse to implement readBodyBuffer"); + } + return { + offset, + count, + buffer: yield partRes.readBodyBuffer() + }; + }); + } + function downloadCacheStorageSDK(archiveLocation, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const client = new storage_blob_1.BlockBlobClient(archiveLocation, void 0, { + retryOptions: { + // Override the timeout used when downloading each 4 MB chunk + // The default is 2 min / MB, which is way too slow + tryTimeoutInMs: options.timeoutInMs + } + }); + const properties = yield client.getProperties(); + const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; + if (contentLength < 0) { + core12.debug("Unable to determine content length, downloading file with http-client..."); + yield downloadCacheHttpClient(archiveLocation, archivePath); + } else { + const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); + const downloadProgress = new DownloadProgress(contentLength); + const fd = fs.openSync(archivePath, "w"); + try { + downloadProgress.startDisplayTimer(); + const controller = new abort_controller_1.AbortController(); + const abortSignal = controller.signal; + while (!downloadProgress.isDone()) { + const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; + const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); + downloadProgress.nextSegment(segmentSize); + const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 36e5, client.downloadToBuffer(segmentStart, segmentSize, { + abortSignal, + concurrency: options.downloadConcurrency, + onProgress: downloadProgress.onProgress() + })); + if (result === "timeout") { + controller.abort(); + throw new Error("Aborting cache download as the download time exceeded the timeout."); + } else if (Buffer.isBuffer(result)) { + fs.writeFileSync(fd, result); + } + } + } finally { + downloadProgress.stopDisplayTimer(); + fs.closeSync(fd); + } + } + }); + } + exports2.downloadCacheStorageSDK = downloadCacheStorageSDK; + var promiseWithTimeout = (timeoutMs, promise) => __awaiter4(void 0, void 0, void 0, function* () { + let timeoutHandle; + const timeoutPromise = new Promise((resolve2) => { + timeoutHandle = setTimeout(() => resolve2("timeout"), timeoutMs); + }); + return Promise.race([promise, timeoutPromise]).then((result) => { + clearTimeout(timeoutHandle); + return result; + }); + }); + } +}); + +// node_modules/@actions/cache/lib/options.js +var require_options = __commonJS({ + "node_modules/@actions/cache/lib/options.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getDownloadOptions = exports2.getUploadOptions = void 0; + var core12 = __importStar4(require_core()); + function getUploadOptions(copy) { + const result = { + useAzureSdk: false, + uploadConcurrency: 4, + uploadChunkSize: 32 * 1024 * 1024 + }; + if (copy) { + if (typeof copy.useAzureSdk === "boolean") { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.uploadConcurrency === "number") { + result.uploadConcurrency = copy.uploadConcurrency; + } + if (typeof copy.uploadChunkSize === "number") { + result.uploadChunkSize = copy.uploadChunkSize; + } + } + result.uploadConcurrency = !isNaN(Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) ? Math.min(32, Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) : result.uploadConcurrency; + result.uploadChunkSize = !isNaN(Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"])) ? Math.min(128 * 1024 * 1024, Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"]) * 1024 * 1024) : result.uploadChunkSize; + core12.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core12.debug(`Upload concurrency: ${result.uploadConcurrency}`); + core12.debug(`Upload chunk size: ${result.uploadChunkSize}`); + return result; + } + exports2.getUploadOptions = getUploadOptions; + function getDownloadOptions(copy) { + const result = { + useAzureSdk: false, + concurrentBlobDownloads: true, + downloadConcurrency: 8, + timeoutInMs: 3e4, + segmentTimeoutInMs: 6e5, + lookupOnly: false + }; + if (copy) { + if (typeof copy.useAzureSdk === "boolean") { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.concurrentBlobDownloads === "boolean") { + result.concurrentBlobDownloads = copy.concurrentBlobDownloads; + } + if (typeof copy.downloadConcurrency === "number") { + result.downloadConcurrency = copy.downloadConcurrency; + } + if (typeof copy.timeoutInMs === "number") { + result.timeoutInMs = copy.timeoutInMs; + } + if (typeof copy.segmentTimeoutInMs === "number") { + result.segmentTimeoutInMs = copy.segmentTimeoutInMs; + } + if (typeof copy.lookupOnly === "boolean") { + result.lookupOnly = copy.lookupOnly; + } + } + const segmentDownloadTimeoutMins = process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]; + if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) { + result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1e3; + } + core12.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core12.debug(`Download concurrency: ${result.downloadConcurrency}`); + core12.debug(`Request timeout (ms): ${result.timeoutInMs}`); + core12.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`); + core12.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); + core12.debug(`Lookup only: ${result.lookupOnly}`); + return result; + } + exports2.getDownloadOptions = getDownloadOptions; + } +}); + +// node_modules/@actions/cache/lib/internal/config.js +var require_config = __commonJS({ + "node_modules/@actions/cache/lib/internal/config.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getCacheServiceURL = exports2.getCacheServiceVersion = exports2.isGhes = void 0; + function isGhes() { + const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com"); + const hostname = ghUrl.hostname.trimEnd().toUpperCase(); + const isGitHubHost = hostname === "GITHUB.COM"; + const isGheHost = hostname.endsWith(".GHE.COM"); + const isLocalHost = hostname.endsWith(".LOCALHOST"); + return !isGitHubHost && !isGheHost && !isLocalHost; + } + exports2.isGhes = isGhes; + function getCacheServiceVersion() { + if (isGhes()) + return "v1"; + return process.env["ACTIONS_CACHE_SERVICE_V2"] ? "v2" : "v1"; + } + exports2.getCacheServiceVersion = getCacheServiceVersion; + function getCacheServiceURL() { + const version = getCacheServiceVersion(); + switch (version) { + case "v1": + return process.env["ACTIONS_CACHE_URL"] || process.env["ACTIONS_RESULTS_URL"] || ""; + case "v2": + return process.env["ACTIONS_RESULTS_URL"] || ""; + default: + throw new Error(`Unsupported cache service version: ${version}`); + } + } + exports2.getCacheServiceURL = getCacheServiceURL; + } +}); + +// node_modules/@actions/cache/package.json +var require_package2 = __commonJS({ + "node_modules/@actions/cache/package.json"(exports2, module2) { + module2.exports = { + name: "@actions/cache", + version: "4.1.0", + preview: true, + description: "Actions cache lib", + keywords: [ + "github", + "actions", + "cache" + ], + homepage: "https://github.com/actions/toolkit/tree/main/packages/cache", + license: "MIT", + main: "lib/cache.js", + types: "lib/cache.d.ts", + directories: { + lib: "lib", + test: "__tests__" + }, + files: [ + "lib", + "!.DS_Store" + ], + publishConfig: { + access: "public" + }, + repository: { + type: "git", + url: "git+https://github.com/actions/toolkit.git", + directory: "packages/cache" + }, + scripts: { + "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", + test: 'echo "Error: run tests from root" && exit 1', + tsc: "tsc" + }, + bugs: { + url: "https://github.com/actions/toolkit/issues" + }, + dependencies: { + "@actions/core": "^1.11.1", + "@actions/exec": "^1.0.1", + "@actions/glob": "^0.1.0", + "@protobuf-ts/runtime-rpc": "^2.11.1", + "@actions/http-client": "^2.1.1", + "@actions/io": "^1.0.1", + "@azure/abort-controller": "^1.1.0", + "@azure/ms-rest-js": "^2.6.0", + "@azure/storage-blob": "^12.13.0", + semver: "^6.3.1" + }, + devDependencies: { + "@types/node": "^22.13.9", + "@types/semver": "^6.0.0", + "@protobuf-ts/plugin": "^2.9.4", + typescript: "^5.2.2" + } + }; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/user-agent.js +var require_user_agent = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/user-agent.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getUserAgentString = void 0; + var packageJson = require_package2(); + function getUserAgentString() { + return `@actions/cache-${packageJson.version}`; + } + exports2.getUserAgentString = getUserAgentString; + } +}); + +// node_modules/@actions/cache/lib/internal/cacheHttpClient.js +var require_cacheHttpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/cacheHttpClient.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; + var core12 = __importStar4(require_core()); + var http_client_1 = require_lib(); + var auth_1 = require_auth(); + var fs = __importStar4(require("fs")); + var url_1 = require("url"); + var utils = __importStar4(require_cacheUtils()); + var uploadUtils_1 = require_uploadUtils(); + var downloadUtils_1 = require_downloadUtils(); + var options_1 = require_options(); + var requestUtils_1 = require_requestUtils(); + var config_1 = require_config(); + var user_agent_1 = require_user_agent(); + function getCacheApiUrl(resource) { + const baseUrl = (0, config_1.getCacheServiceURL)(); + if (!baseUrl) { + throw new Error("Cache Service Url not found, unable to restore cache."); + } + const url = `${baseUrl}_apis/artifactcache/${resource}`; + core12.debug(`Resource Url: ${url}`); + return url; + } + function createAcceptHeader(type2, apiVersion) { + return `${type2};api-version=${apiVersion}`; + } + function getRequestOptions() { + const requestOptions = { + headers: { + Accept: createAcceptHeader("application/json", "6.0-preview.1") + } + }; + return requestOptions; + } + function createHttpClient() { + const token = process.env["ACTIONS_RUNTIME_TOKEN"] || ""; + const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); + return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions()); + } + function getCacheEntry(keys, paths, options) { + return __awaiter4(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); + const resource = `cache?keys=${encodeURIComponent(keys.join(","))}&version=${version}`; + const response = yield (0, requestUtils_1.retryTypedResponse)("getCacheEntry", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.getJson(getCacheApiUrl(resource)); + })); + if (response.statusCode === 204) { + if (core12.isDebug()) { + yield printCachesListForDiagnostics(keys[0], httpClient, version); + } + return null; + } + if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) { + throw new Error(`Cache service responded with ${response.statusCode}`); + } + const cacheResult = response.result; + const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; + if (!cacheDownloadUrl) { + throw new Error("Cache not found."); + } + core12.setSecret(cacheDownloadUrl); + core12.debug(`Cache Result:`); + core12.debug(JSON.stringify(cacheResult)); + return cacheResult; + }); + } + exports2.getCacheEntry = getCacheEntry; + function printCachesListForDiagnostics(key, httpClient, version) { + return __awaiter4(this, void 0, void 0, function* () { + const resource = `caches?key=${encodeURIComponent(key)}`; + const response = yield (0, requestUtils_1.retryTypedResponse)("listCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.getJson(getCacheApiUrl(resource)); + })); + if (response.statusCode === 200) { + const cacheListResult = response.result; + const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount; + if (totalCount && totalCount > 0) { + core12.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key +Other caches with similar key:`); + for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) { + core12.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); + } + } + } + }); + } + function downloadCache(archiveLocation, archivePath, options) { + return __awaiter4(this, void 0, void 0, function* () { + const archiveUrl = new url_1.URL(archiveLocation); + const downloadOptions = (0, options_1.getDownloadOptions)(options); + if (archiveUrl.hostname.endsWith(".blob.core.windows.net")) { + if (downloadOptions.useAzureSdk) { + yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions); + } else if (downloadOptions.concurrentBlobDownloads) { + yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions); + } else { + yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); + } + } else { + yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); + } + }); + } + exports2.downloadCache = downloadCache; + function reserveCache(key, paths, options) { + return __awaiter4(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); + const reserveCacheRequest = { + key, + version, + cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize + }; + const response = yield (0, requestUtils_1.retryTypedResponse)("reserveCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl("caches"), reserveCacheRequest); + })); + return response; + }); + } + exports2.reserveCache = reserveCache; + function getContentRange(start, end) { + return `bytes ${start}-${end}/*`; + } + function uploadChunk(httpClient, resourceUrl, openStream, start, end) { + return __awaiter4(this, void 0, void 0, function* () { + core12.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); + const additionalHeaders = { + "Content-Type": "application/octet-stream", + "Content-Range": getContentRange(start, end) + }; + const uploadChunkResponse = yield (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.sendStream("PATCH", resourceUrl, openStream(), additionalHeaders); + })); + if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) { + throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); + } + }); + } + function uploadFile(httpClient, cacheId, archivePath, options) { + return __awaiter4(this, void 0, void 0, function* () { + const fileSize = utils.getArchiveFileSizeInBytes(archivePath); + const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); + const fd = fs.openSync(archivePath, "r"); + const uploadOptions = (0, options_1.getUploadOptions)(options); + const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency); + const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize); + const parallelUploads = [...new Array(concurrency).keys()]; + core12.debug("Awaiting all uploads"); + let offset = 0; + try { + yield Promise.all(parallelUploads.map(() => __awaiter4(this, void 0, void 0, function* () { + while (offset < fileSize) { + const chunkSize = Math.min(fileSize - offset, maxChunkSize); + const start = offset; + const end = offset + chunkSize - 1; + offset += maxChunkSize; + yield uploadChunk(httpClient, resourceUrl, () => fs.createReadStream(archivePath, { + fd, + start, + end, + autoClose: false + }).on("error", (error2) => { + throw new Error(`Cache upload failed because file read failed with ${error2.message}`); + }), start, end); + } + }))); + } finally { + fs.closeSync(fd); + } + return; + }); + } + function commitCache(httpClient, cacheId, filesize) { + return __awaiter4(this, void 0, void 0, function* () { + const commitCacheRequest = { size: filesize }; + return yield (0, requestUtils_1.retryTypedResponse)("commitCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); + })); + }); + } + function saveCache3(cacheId, archivePath, signedUploadURL, options) { + return __awaiter4(this, void 0, void 0, function* () { + const uploadOptions = (0, options_1.getUploadOptions)(options); + if (uploadOptions.useAzureSdk) { + if (!signedUploadURL) { + throw new Error("Azure Storage SDK can only be used when a signed URL is provided."); + } + yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options); + } else { + const httpClient = createHttpClient(); + core12.debug("Upload cache"); + yield uploadFile(httpClient, cacheId, archivePath, options); + core12.debug("Commiting cache"); + const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); + const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); + if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) { + throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); + } + core12.info("Cache saved successfully"); + } + }); + } + exports2.saveCache = saveCache3; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js +var require_json_typings = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isJsonObject = exports2.typeofJsonValue = void 0; + function typeofJsonValue(value) { + let t = typeof value; + if (t == "object") { + if (Array.isArray(value)) + return "array"; + if (value === null) + return "null"; + } + return t; + } + exports2.typeofJsonValue = typeofJsonValue; + function isJsonObject(value) { + return value !== null && typeof value == "object" && !Array.isArray(value); + } + exports2.isJsonObject = isJsonObject; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/base64.js +var require_base642 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/base64.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.base64encode = exports2.base64decode = void 0; + var encTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); + var decTable = []; + for (let i = 0; i < encTable.length; i++) + decTable[encTable[i].charCodeAt(0)] = i; + decTable["-".charCodeAt(0)] = encTable.indexOf("+"); + decTable["_".charCodeAt(0)] = encTable.indexOf("/"); + function base64decode(base64Str) { + let es = base64Str.length * 3 / 4; + if (base64Str[base64Str.length - 2] == "=") + es -= 2; + else if (base64Str[base64Str.length - 1] == "=") + es -= 1; + let bytes = new Uint8Array(es), bytePos = 0, groupPos = 0, b, p = 0; + for (let i = 0; i < base64Str.length; i++) { + b = decTable[base64Str.charCodeAt(i)]; + if (b === void 0) { + switch (base64Str[i]) { + case "=": + groupPos = 0; + // reset state when padding found + case "\n": + case "\r": + case " ": + case " ": + continue; + // skip white-space, and padding + default: + throw Error(`invalid base64 string.`); + } + } + switch (groupPos) { + case 0: + p = b; + groupPos = 1; + break; + case 1: + bytes[bytePos++] = p << 2 | (b & 48) >> 4; + p = b; + groupPos = 2; + break; + case 2: + bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; + p = b; + groupPos = 3; + break; + case 3: + bytes[bytePos++] = (p & 3) << 6 | b; + groupPos = 0; + break; + } + } + if (groupPos == 1) + throw Error(`invalid base64 string.`); + return bytes.subarray(0, bytePos); + } + exports2.base64decode = base64decode; + function base64encode(bytes) { + let base64 = "", groupPos = 0, b, p = 0; + for (let i = 0; i < bytes.length; i++) { + b = bytes[i]; + switch (groupPos) { + case 0: + base64 += encTable[b >> 2]; + p = (b & 3) << 4; + groupPos = 1; + break; + case 1: + base64 += encTable[p | b >> 4]; + p = (b & 15) << 2; + groupPos = 2; + break; + case 2: + base64 += encTable[p | b >> 6]; + base64 += encTable[b & 63]; + groupPos = 0; + break; + } + } + if (groupPos) { + base64 += encTable[p]; + base64 += "="; + if (groupPos == 1) + base64 += "="; + } + return base64; + } + exports2.base64encode = base64encode; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js +var require_protobufjs_utf8 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.utf8read = void 0; + var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); + function utf8read(bytes) { + if (bytes.length < 1) + return ""; + let pos = 0, parts = [], chunk = [], i = 0, t; + let len = bytes.length; + while (pos < len) { + t = bytes[pos++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536; + chunk[i++] = 55296 + (t >> 10); + chunk[i++] = 56320 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; + if (i > 8191) { + parts.push(fromCharCodes(chunk)); + i = 0; + } + } + if (parts.length) { + if (i) + parts.push(fromCharCodes(chunk.slice(0, i))); + return parts.join(""); + } + return fromCharCodes(chunk.slice(0, i)); + } + exports2.utf8read = utf8read; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js +var require_binary_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0; + var UnknownFieldHandler; + (function(UnknownFieldHandler2) { + UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown"); + UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => { + let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = []; + container.push({ no: fieldNo, wireType, data }); + }; + UnknownFieldHandler2.onWrite = (typeName, message, writer) => { + for (let { no, wireType, data } of UnknownFieldHandler2.list(message)) + writer.tag(no, wireType).raw(data); + }; + UnknownFieldHandler2.list = (message, fieldNo) => { + if (is(message)) { + let all = message[UnknownFieldHandler2.symbol]; + return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all; + } + return []; + }; + UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0]; + const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]); + })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {})); + function mergeBinaryOptions(a, b) { + return Object.assign(Object.assign({}, a), b); + } + exports2.mergeBinaryOptions = mergeBinaryOptions; + var WireType; + (function(WireType2) { + WireType2[WireType2["Varint"] = 0] = "Varint"; + WireType2[WireType2["Bit64"] = 1] = "Bit64"; + WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited"; + WireType2[WireType2["StartGroup"] = 3] = "StartGroup"; + WireType2[WireType2["EndGroup"] = 4] = "EndGroup"; + WireType2[WireType2["Bit32"] = 5] = "Bit32"; + })(WireType = exports2.WireType || (exports2.WireType = {})); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js +var require_goog_varint = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0; + function varint64read() { + let lowBits = 0; + let highBits = 0; + for (let shift = 0; shift < 28; shift += 7) { + let b = this.buf[this.pos++]; + lowBits |= (b & 127) << shift; + if ((b & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + } + let middleByte = this.buf[this.pos++]; + lowBits |= (middleByte & 15) << 28; + highBits = (middleByte & 112) >> 4; + if ((middleByte & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + for (let shift = 3; shift <= 31; shift += 7) { + let b = this.buf[this.pos++]; + highBits |= (b & 127) << shift; + if ((b & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + } + throw new Error("invalid varint"); + } + exports2.varint64read = varint64read; + function varint64write(lo, hi, bytes) { + for (let i = 0; i < 28; i = i + 7) { + const shift = lo >>> i; + const hasNext = !(shift >>> 7 == 0 && hi == 0); + const byte = (hasNext ? shift | 128 : shift) & 255; + bytes.push(byte); + if (!hasNext) { + return; + } + } + const splitBits = lo >>> 28 & 15 | (hi & 7) << 4; + const hasMoreBits = !(hi >> 3 == 0); + bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255); + if (!hasMoreBits) { + return; + } + for (let i = 3; i < 31; i = i + 7) { + const shift = hi >>> i; + const hasNext = !(shift >>> 7 == 0); + const byte = (hasNext ? shift | 128 : shift) & 255; + bytes.push(byte); + if (!hasNext) { + return; + } + } + bytes.push(hi >>> 31 & 1); + } + exports2.varint64write = varint64write; + var TWO_PWR_32_DBL = (1 << 16) * (1 << 16); + function int64fromString(dec) { + let minus = dec[0] == "-"; + if (minus) + dec = dec.slice(1); + const base = 1e6; + let lowBits = 0; + let highBits = 0; + function add1e6digit(begin, end) { + const digit1e6 = Number(dec.slice(begin, end)); + highBits *= base; + lowBits = lowBits * base + digit1e6; + if (lowBits >= TWO_PWR_32_DBL) { + highBits = highBits + (lowBits / TWO_PWR_32_DBL | 0); + lowBits = lowBits % TWO_PWR_32_DBL; + } + } + add1e6digit(-24, -18); + add1e6digit(-18, -12); + add1e6digit(-12, -6); + add1e6digit(-6); + return [minus, lowBits, highBits]; + } + exports2.int64fromString = int64fromString; + function int64toString(bitsLow, bitsHigh) { + if (bitsHigh >>> 0 <= 2097151) { + return "" + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); + } + let low = bitsLow & 16777215; + let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215; + let high = bitsHigh >> 16 & 65535; + let digitA = low + mid * 6777216 + high * 6710656; + let digitB = mid + high * 8147497; + let digitC = high * 2; + let base = 1e7; + if (digitA >= base) { + digitB += Math.floor(digitA / base); + digitA %= base; + } + if (digitB >= base) { + digitC += Math.floor(digitB / base); + digitB %= base; + } + function decimalFrom1e7(digit1e7, needLeadingZeros) { + let partial = digit1e7 ? String(digit1e7) : ""; + if (needLeadingZeros) { + return "0000000".slice(partial.length) + partial; + } + return partial; + } + return decimalFrom1e7( + digitC, + /*needLeadingZeros=*/ + 0 + ) + decimalFrom1e7( + digitB, + /*needLeadingZeros=*/ + digitC + ) + // If the final 1e7 digit didn't need leading zeros, we would have + // returned via the trivial code path at the top. + decimalFrom1e7( + digitA, + /*needLeadingZeros=*/ + 1 + ); + } + exports2.int64toString = int64toString; + function varint32write(value, bytes) { + if (value >= 0) { + while (value > 127) { + bytes.push(value & 127 | 128); + value = value >>> 7; + } + bytes.push(value); + } else { + for (let i = 0; i < 9; i++) { + bytes.push(value & 127 | 128); + value = value >> 7; + } + bytes.push(1); + } + } + exports2.varint32write = varint32write; + function varint32read() { + let b = this.buf[this.pos++]; + let result = b & 127; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 7; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 14; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 21; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 15) << 28; + for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++) + b = this.buf[this.pos++]; + if ((b & 128) != 0) + throw new Error("invalid varint"); + this.assertBounds(); + return result >>> 0; + } + exports2.varint32read = varint32read; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js +var require_pb_long = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0; + var goog_varint_1 = require_goog_varint(); + var BI; + function detectBi() { + const dv = new DataView(new ArrayBuffer(8)); + const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; + BI = ok ? { + MIN: BigInt("-9223372036854775808"), + MAX: BigInt("9223372036854775807"), + UMIN: BigInt("0"), + UMAX: BigInt("18446744073709551615"), + C: BigInt, + V: dv + } : void 0; + } + exports2.detectBi = detectBi; + detectBi(); + function assertBi(bi) { + if (!bi) + throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); + } + var RE_DECIMAL_STR = /^-?[0-9]+$/; + var TWO_PWR_32_DBL = 4294967296; + var HALF_2_PWR_32 = 2147483648; + var SharedPbLong = class { + /** + * Create a new instance with the given bits. + */ + constructor(lo, hi) { + this.lo = lo | 0; + this.hi = hi | 0; + } + /** + * Is this instance equal to 0? + */ + isZero() { + return this.lo == 0 && this.hi == 0; + } + /** + * Convert to a native number. + */ + toNumber() { + let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); + if (!Number.isSafeInteger(result)) + throw new Error("cannot convert to safe number"); + return result; + } + }; + var PbULong = class _PbULong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error("string is no integer"); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.UMIN) + throw new Error("signed value for ulong"); + if (value > BI.UMAX) + throw new Error("ulong too large"); + BI.V.setBigUint64(0, value, true); + return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + } + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error("string is no integer"); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) + throw new Error("signed value for ulong"); + return new _PbULong(lo, hi); + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error("number is no integer"); + if (value < 0) + throw new Error("signed value for ulong"); + return new _PbULong(value, value / TWO_PWR_32_DBL); + } + throw new Error("unknown value " + typeof value); + } + /** + * Convert to decimal string. + */ + toString() { + return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); + } + /** + * Convert to native bigint. + */ + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigUint64(0, true); + } + }; + exports2.PbULong = PbULong; + PbULong.ZERO = new PbULong(0, 0); + var PbLong = class _PbLong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error("string is no integer"); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.MIN) + throw new Error("signed long too small"); + if (value > BI.MAX) + throw new Error("signed long too large"); + BI.V.setBigInt64(0, value, true); + return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + } + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error("string is no integer"); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) { + if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0) + throw new Error("signed long too small"); + } else if (hi >= HALF_2_PWR_32) + throw new Error("signed long too large"); + let pbl = new _PbLong(lo, hi); + return minus ? pbl.negate() : pbl; + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error("number is no integer"); + return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL) : new _PbLong(-value, -value / TWO_PWR_32_DBL).negate(); + } + throw new Error("unknown value " + typeof value); + } + /** + * Do we have a minus sign? + */ + isNegative() { + return (this.hi & HALF_2_PWR_32) !== 0; + } + /** + * Negate two's complement. + * Invert all the bits and add one to the result. + */ + negate() { + let hi = ~this.hi, lo = this.lo; + if (lo) + lo = ~lo + 1; + else + hi += 1; + return new _PbLong(lo, hi); + } + /** + * Convert to decimal string. + */ + toString() { + if (BI) + return this.toBigInt().toString(); + if (this.isNegative()) { + let n = this.negate(); + return "-" + goog_varint_1.int64toString(n.lo, n.hi); + } + return goog_varint_1.int64toString(this.lo, this.hi); + } + /** + * Convert to native bigint. + */ + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigInt64(0, true); + } + }; + exports2.PbLong = PbLong; + PbLong.ZERO = new PbLong(0, 0); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js +var require_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryReader = exports2.binaryReadOptions = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var defaultsRead = { + readUnknownField: true, + readerFactory: (bytes) => new BinaryReader(bytes) + }; + function binaryReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; + } + exports2.binaryReadOptions = binaryReadOptions; + var BinaryReader = class { + constructor(buf, textDecoder) { + this.varint64 = goog_varint_1.varint64read; + this.uint32 = goog_varint_1.varint32read; + this.buf = buf; + this.len = buf.length; + this.pos = 0; + this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true + }); + } + /** + * Reads a tag - field number and wire type. + */ + tag() { + let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; + if (fieldNo <= 0 || wireType < 0 || wireType > 5) + throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); + return [fieldNo, wireType]; + } + /** + * Skip one element on the wire and return the skipped data. + * Supports WireType.StartGroup since v2.0.0-alpha.23. + */ + skip(wireType) { + let start = this.pos; + switch (wireType) { + case binary_format_contract_1.WireType.Varint: + while (this.buf[this.pos++] & 128) { + } + break; + case binary_format_contract_1.WireType.Bit64: + this.pos += 4; + case binary_format_contract_1.WireType.Bit32: + this.pos += 4; + break; + case binary_format_contract_1.WireType.LengthDelimited: + let len = this.uint32(); + this.pos += len; + break; + case binary_format_contract_1.WireType.StartGroup: + let t; + while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { + this.skip(t); + } + break; + default: + throw new Error("cant skip wire type " + wireType); + } + this.assertBounds(); + return this.buf.subarray(start, this.pos); + } + /** + * Throws error if position in byte array is out of range. + */ + assertBounds() { + if (this.pos > this.len) + throw new RangeError("premature EOF"); + } + /** + * Read a `int32` field, a signed 32 bit varint. + */ + int32() { + return this.uint32() | 0; + } + /** + * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. + */ + sint32() { + let zze = this.uint32(); + return zze >>> 1 ^ -(zze & 1); + } + /** + * Read a `int64` field, a signed 64-bit varint. + */ + int64() { + return new pb_long_1.PbLong(...this.varint64()); + } + /** + * Read a `uint64` field, an unsigned 64-bit varint. + */ + uint64() { + return new pb_long_1.PbULong(...this.varint64()); + } + /** + * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. + */ + sint64() { + let [lo, hi] = this.varint64(); + let s = -(lo & 1); + lo = (lo >>> 1 | (hi & 1) << 31) ^ s; + hi = hi >>> 1 ^ s; + return new pb_long_1.PbLong(lo, hi); + } + /** + * Read a `bool` field, a variant. + */ + bool() { + let [lo, hi] = this.varint64(); + return lo !== 0 || hi !== 0; + } + /** + * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. + */ + fixed32() { + return this.view.getUint32((this.pos += 4) - 4, true); + } + /** + * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. + */ + sfixed32() { + return this.view.getInt32((this.pos += 4) - 4, true); + } + /** + * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. + */ + fixed64() { + return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); + } + /** + * Read a `fixed64` field, a signed, fixed-length 64-bit integer. + */ + sfixed64() { + return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); + } + /** + * Read a `float` field, 32-bit floating point number. + */ + float() { + return this.view.getFloat32((this.pos += 4) - 4, true); + } + /** + * Read a `double` field, a 64-bit floating point number. + */ + double() { + return this.view.getFloat64((this.pos += 8) - 8, true); + } + /** + * Read a `bytes` field, length-delimited arbitrary data. + */ + bytes() { + let len = this.uint32(); + let start = this.pos; + this.pos += len; + this.assertBounds(); + return this.buf.subarray(start, start + len); + } + /** + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); + } + }; + exports2.BinaryReader = BinaryReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js +var require_assert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; + function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } + } + exports2.assert = assert; + function assertNever2(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + } + exports2.assertNever = assertNever2; + var FLOAT32_MAX = 34028234663852886e22; + var FLOAT32_MIN = -34028234663852886e22; + var UINT32_MAX = 4294967295; + var INT32_MAX = 2147483647; + var INT32_MIN = -2147483648; + function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid int 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error("invalid int 32: " + arg); + } + exports2.assertInt32 = assertInt32; + function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid uint 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error("invalid uint 32: " + arg); + } + exports2.assertUInt32 = assertUInt32; + function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error("invalid float 32: " + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error("invalid float 32: " + arg); + } + exports2.assertFloat32 = assertFloat32; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js +var require_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var assert_1 = require_assert(); + var defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter() + }; + function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.binaryWriteOptions = binaryWriteOptions; + var BinaryWriter = class { + constructor(textEncoder) { + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; + } + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + let chunk = this.finish(); + let prev = this.stack.pop(); + if (!prev) + throw new Error("invalid state, fork stack empty"); + this.chunks = prev.chunks; + this.buf = prev.buf; + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type2) { + return this.uint32((fieldNo << 3 | type2) >>> 0); + } + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; + } + this.chunks.push(chunk); + return this; + } + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + while (value > 127) { + this.buf.push(value & 127 | 128); + value = value >>> 7; + } + this.buf.push(value); + return this; + } + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + value = (value << 1 ^ value >> 31) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + */ + sint64(value) { + let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + }; + exports2.BinaryWriter = BinaryWriter; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js +var require_json_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; + var defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0 + }; + var defaultsRead = { + ignoreUnknownFields: false + }; + function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; + } + exports2.jsonReadOptions = jsonReadOptions; + function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.jsonWriteOptions = jsonWriteOptions; + function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + return c; + } + exports2.mergeJsonOptions = mergeJsonOptions; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js +var require_message_type_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MESSAGE_TYPE = void 0; + exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js +var require_lower_camel_case = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.lowerCamelCase = void 0; + function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == "_") { + capNext = true; + } else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } else if (i == 0) { + sb.push(next.toLowerCase()); + } else { + sb.push(next); + } + } + return sb.join(""); + } + exports2.lowerCamelCase = lowerCamelCase; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js +var require_reflection_info = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; + var lower_camel_case_1 = require_lower_camel_case(); + var ScalarType; + (function(ScalarType2) { + ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; + ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; + ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; + ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; + ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; + ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; + ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; + ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; + ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; + ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; + ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; + ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; + ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; + ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; + ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; + })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); + var LongType; + (function(LongType2) { + LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; + LongType2[LongType2["STRING"] = 1] = "STRING"; + LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; + })(LongType = exports2.LongType || (exports2.LongType = {})); + var RepeatType; + (function(RepeatType2) { + RepeatType2[RepeatType2["NO"] = 0] = "NO"; + RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; + RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; + })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); + function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + return field; + } + exports2.normalizeFieldInfo = normalizeFieldInfo; + function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readFieldOptions = readFieldOptions; + function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readFieldOption = readFieldOption; + function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMessageOption = readMessageOption; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js +var require_oneof = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; + function isOneofGroup(any) { + if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === void 0) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; + } + } + exports2.isOneofGroup = isOneofGroup; + function getOneofValue(oneof, kind) { + return oneof[kind]; + } + exports2.getOneofValue = getOneofValue; + function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== void 0) { + oneof[kind] = value; + } + } + exports2.setOneofValue = setOneofValue; + function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== void 0 && kind !== void 0) { + oneof[kind] = value; + } + } + exports2.setUnknownOneofValue = setUnknownOneofValue; + function clearOneofValue(oneof) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = void 0; + } + exports2.clearOneofValue = clearOneofValue; + function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === void 0) { + return void 0; + } + return oneof[oneof.oneofKind]; + } + exports2.getSelectedOneofValue = getSelectedOneofValue; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js +var require_reflection_type_check = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionTypeCheck = void 0; + var reflection_info_1 = require_reflection_info(); + var oneof_1 = require_oneof(); + var ReflectionTypeCheck = class { + constructor(info4) { + var _a; + this.fields = (_a = info4.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } + } + } + this.data = { req, known, oneofs: Object.values(oneofs) }; + } + /** + * Is the argument a valid message as specified by the + * reflection information? + * + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. + * + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. + */ + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === void 0 || typeof message != "object") + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + if (keys.some((k) => !data.known.includes(k))) + return false; + } + if (depth < 1) { + return true; + } + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === void 0) + continue; + const field = this.fields.find((f) => f.localName === group.oneofKind); + if (!field) + return false; + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + for (const field of this.fields) { + if (field.oneof !== void 0) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; + } + return true; + } + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === void 0) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != "object" || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } + break; + } + return true; + } + message(arg, type2, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type2.isAssignable(arg, depth); + } + return type2.is(arg, depth); + } + messages(arg, type2, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.isAssignable(arg[i], depth - 1)) + return false; + } else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type2, longType) { + let argType = typeof arg; + switch (type2) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == "boolean"; + case reflection_info_1.ScalarType.STRING: + return argType == "string"; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == "number" && !isNaN(arg); + default: + return argType == "number" && Number.isInteger(arg); + } + } + scalars(arg, type2, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type2, longType)) + return false; + } + return true; + } + mapKeys(map2, type2, depth) { + let keys = Object.keys(map2); + switch (type2) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); + default: + return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + } + } + }; + exports2.ReflectionTypeCheck = ReflectionTypeCheck; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js +var require_reflection_long_convert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionLongConvert = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionLongConvert(long, type2) { + switch (type2) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + return long.toString(); + } + } + exports2.reflectionLongConvert = reflectionLongConvert; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js +var require_reflection_json_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonReader = void 0; + var json_typings_1 = require_json_typings(); + var base64_1 = require_base642(); + var reflection_info_1 = require_reflection_info(); + var pb_long_1 = require_pb_long(); + var assert_1 = require_assert(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var ReflectionJsonReader = class { + constructor(info4) { + this.info = info4; + } + prepare() { + var _a; + if (this.fMap === void 0) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } + } + } + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + } + } + /** + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + let target; + if (field.oneof) { + if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { + continue; + } + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } else { + target = message; + } + if (field.kind == "map") { + if (jsonValue === null) { + continue; + } + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + const fieldObj = target[localName]; + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + let val2; + switch (field.V.kind) { + case "message": + val2 = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val2; + } + } else if (field.repeat) { + if (jsonValue === null) + continue; + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + const fieldArr = target[localName]; + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val2; + switch (field.kind) { + case "message": + val2 = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name, jsonValue); + fieldArr.push(val2); + } + } else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { + this.assert(field.oneof === void 0, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + if (jsonValue === null) + continue; + let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + target[localName] = val2; + break; + case "scalar": + if (jsonValue === null) + continue; + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } + } + } + /** + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + */ + enum(type2, json2, fieldName, ignoreUnknownFields) { + if (type2[0] == "google.protobuf.NullValue") + assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); + if (json2 === null) + return 0; + switch (typeof json2) { + case "number": + assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); + return json2; + case "string": + let localEnumName = json2; + if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) + localEnumName = json2.substring(type2[2].length); + let enumNumber = type2[1][localEnumName]; + if (typeof enumNumber === "undefined" && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); + return enumNumber; + } + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); + } + scalar(json2, type2, longType, fieldName) { + let e; + try { + switch (type2) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json2 === null) + return 0; + if (json2 === "NaN") + return Number.NaN; + if (json2 === "Infinity") + return Number.POSITIVE_INFINITY; + if (json2 === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json2 === "") { + e = "empty string"; + break; + } + if (typeof json2 == "string" && json2.trim().length !== json2.length) { + e = "extra whitespace"; + break; + } + if (typeof json2 != "string" && typeof json2 != "number") { + break; + } + let float2 = Number(json2); + if (Number.isNaN(float2)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float2)) { + e = "too large or small"; + break; + } + if (type2 == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float2); + return float2; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json2 === null) + return 0; + let int32; + if (typeof json2 == "number") + int32 = json2; + else if (json2 === "") + e = "empty string"; + else if (typeof json2 == "string") { + if (json2.trim().length !== json2.length) + e = "extra whitespace"; + else + int32 = Number(json2); + } + if (int32 === void 0) + break; + if (type2 == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json2 === null) + return false; + if (typeof json2 !== "boolean") + break; + return json2; + // string: + case reflection_info_1.ScalarType.STRING: + if (json2 === null) + return ""; + if (typeof json2 !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json2); + } catch (e2) { + e2 = "invalid UTF8"; + break; + } + return json2; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json2 === null || json2 === "") + return new Uint8Array(0); + if (typeof json2 !== "string") + break; + return base64_1.base64decode(json2); + } + } catch (error2) { + e = error2.message; + } + this.assert(false, fieldName + (e ? " - " + e : ""), json2); + } + }; + exports2.ReflectionJsonReader = ReflectionJsonReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js +var require_reflection_json_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonWriter = void 0; + var base64_1 = require_base642(); + var pb_long_1 = require_pb_long(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var ReflectionJsonWriter = class { + constructor(info4) { + var _a; + this.fields = (_a = info4.fields) !== null && _a !== void 0 ? _a : []; + } + /** + * Converts the message to a JSON object, based on the field descriptors. + */ + write(message, options) { + const json2 = {}, source = message; + for (const field of this.fields) { + if (!field.oneof) { + let jsonValue2 = this.field(field, source[field.localName], options); + if (jsonValue2 !== void 0) + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; + continue; + } + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; + const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== void 0); + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json2; + } + field(field, value, options) { + let jsonValue = void 0; + if (field.kind == "map") { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); + const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + } + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); + const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val2 = this.message(messageType, value[i], field.name, options); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + } + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; + } + /** + * Returns `null` as the default for google.protobuf.NullValue. + */ + enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type2[0] == "google.protobuf.NullValue") + return !emitDefaultValues && !optional ? void 0 : null; + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + if (value === 0 && !emitDefaultValues && !optional) + return void 0; + assert_1.assert(typeof value == "number"); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type2[1].hasOwnProperty(value)) + return value; + if (type2[2]) + return type2[2] + type2[1][value]; + return type2[1][value]; + } + message(type2, value, fieldName, options) { + if (value === void 0) + return options.emitDefaultValues ? null : void 0; + return type2.internalJsonWrite(value, options); + } + scalar(type2, value, fieldName, optional, emitDefaultValues) { + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + const ed = emitDefaultValues || optional; + switch (type2) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assert(typeof value == "number"); + if (Number.isNaN(value)) + return "NaN"; + if (value === Number.POSITIVE_INFINITY) + return "Infinity"; + if (value === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? "" : void 0; + assert_1.assert(typeof value == "string"); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : void 0; + assert_1.assert(typeof value == "boolean"); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return void 0; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return void 0; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : void 0; + return base64_1.base64encode(value); + } + } + }; + exports2.ReflectionJsonWriter = ReflectionJsonWriter; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js +var require_reflection_scalar_default = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionScalarDefault = void 0; + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var pb_long_1 = require_pb_long(); + function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { + switch (type2) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + return 0; + } + } + exports2.reflectionScalarDefault = reflectionScalarDefault; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js +var require_reflection_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionBinaryReader = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var ReflectionBinaryReader = class { + constructor(info4) { + this.info = info4; + } + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + } + } + /** + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(reader, message, options, length) { + this.prepare(); + const end = length === void 0 ? reader.len : reader.pos + length; + while (reader.pos < end) { + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; + } + let target = message, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + target = target[field.oneof]; + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : void 0; + if (repeated) { + let arr = target[localName]; + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } else + arr.push(this.scalar(reader, T, L)); + } else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + target[localName][mapKey] = mapVal; + break; + } + } + } + /** + * Read a map field, expecting key field = 1, value field = 2 + */ + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = void 0; + let val2 = void 0; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val2 = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val2 = reader.int32(); + break; + case "message": + val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } + } + if (key === void 0) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val2 === void 0) + switch (field.V.kind) { + case "scalar": + val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val2 = 0; + break; + case "message": + val2 = field.V.T().create(); + break; + } + return [key, val2]; + } + scalar(reader, type2, longType) { + switch (type2) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } + } + }; + exports2.ReflectionBinaryReader = ReflectionBinaryReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js +var require_reflection_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionBinaryWriter = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var pb_long_1 = require_pb_long(); + var ReflectionBinaryWriter = class { + constructor(info4) { + this.info = info4; + } + prepare() { + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); + } + } + /** + * Writes the message to binary format. + */ + write(message, writer, options) { + this.prepare(); + for (const field of this.fields) { + let value, emitDefault, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; + value = group[localName]; + emitDefault = true; + } else { + value = message[localName]; + emitDefault = false; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } else if (value === void 0) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == "object" && value !== null); + for (const [key, val2] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val2); + break; + } + } + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); + } + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); + break; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == "true" || key == "false"); + keyValue = key == "true"; + break; + } + this.scalar(writer, field.K, 1, keyValue, true); + switch (field.V.kind) { + case "scalar": + this.scalar(writer, field.V.T, 2, value, true); + break; + case "enum": + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; + case "message": + this.message(writer, options, field.V.T(), 2, value); + break; + } + writer.join(); + } + message(writer, options, handler, fieldNo, value) { + if (value === void 0) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); + } + /** + * Write a single scalar value. + */ + scalar(writer, type2, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type2, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); + } + } + /** + * Write an array of scalar values in packed format. + */ + packed(writer, type2, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let [, method] = this.scalarInfo(type2); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + writer.join(); + } + /** + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. + */ + scalarInfo(type2, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === void 0; + let d = value === 0; + switch (type2) { + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; + case reflection_info_1.ScalarType.STRING: + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; + case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; + case reflection_info_1.ScalarType.FLOAT: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; + case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; + case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; + case reflection_info_1.ScalarType.SINT32: + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; + } + return [t, m, i || d]; + } + }; + exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js +var require_reflection_create = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionCreate = void 0; + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var message_type_contract_1 = require_message_type_contract(); + function reflectionCreate(type2) { + const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); + for (let field of type2.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: void 0 }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } + } + return msg; + } + exports2.reflectionCreate = reflectionCreate; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js +var require_reflection_merge_partial = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionMergePartial = void 0; + function reflectionMergePartial(info4, target, source) { + let fieldValue, input = source, output; + for (let field of info4.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { + continue; + } + fieldValue = group[name]; + output = target[field.oneof]; + output.oneofKind = group.oneofKind; + if (fieldValue == void 0) { + delete output[name]; + continue; + } + } else { + fieldValue = input[name]; + output = target; + if (fieldValue == void 0) { + continue; + } + } + if (field.repeat) + output[name].length = fieldValue.length; + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; + else + output[name] = fieldValue; + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === void 0) + output[name] = T.create(fieldValue); + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); + break; + case "message": + let T2 = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T2.create(fieldValue[k]); + break; + } + break; + } + } + } + exports2.reflectionMergePartial = reflectionMergePartial; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js +var require_reflection_equals = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionEquals = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionEquals(info4, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info4.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) + return false; + break; + } + } + return true; + } + exports2.reflectionEquals = reflectionEquals; + var objectValues = Object.values; + function primitiveEq(type2, a, b) { + if (a === b) + return true; + if (type2 !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; + } + function repeatedPrimitiveEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type2, a[i], b[i])) + return false; + return true; + } + function repeatedMsgEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type2.equals(a[i], b[i])) + return false; + return true; + } + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js +var require_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_type_check_1 = require_reflection_type_check(); + var reflection_json_reader_1 = require_reflection_json_reader(); + var reflection_json_writer_1 = require_reflection_json_writer(); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + var reflection_create_1 = require_reflection_create(); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + var json_typings_1 = require_json_typings(); + var json_format_contract_1 = require_json_format_contract(); + var reflection_equals_1 = require_reflection_equals(); + var binary_writer_1 = require_binary_writer(); + var binary_reader_1 = require_binary_reader(); + var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); + var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; + var MessageType = class { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + messageTypeDescriptor.value = this; + this.messagePrototype = Object.create(null, baseDescriptors); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); + } + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== void 0) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); + } + return message; + } + /** + * Clone the message. + * + * Unknown fields are discarded. + */ + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; + } + /** + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); + } + /** + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); + } + /** + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); + } + /** + * Copy partial data into the target message. + */ + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); + } + /** + * Create a new message from binary format. + */ + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + } + /** + * Read a new message from a JSON value. + */ + fromJson(json2, options) { + return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + } + /** + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. + */ + fromJsonString(json2, options) { + let value = JSON.parse(json2); + return this.fromJson(value, options); + } + /** + * Write the message to canonical JSON value. + */ + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + } + /** + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` + */ + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + } + /** + * Write the message to binary format. + */ + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + } + /** + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. + */ + internalJsonRead(json2, options, target) { + if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json2, message, options); + return message; + } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); + } + /** + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). + * + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. + * + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. + */ + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; + } + /** + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. + * + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. + */ + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; + } + }; + exports2.MessageType = MessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js +var require_reflection_contains_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.containsMessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; + } + exports2.containsMessageType = containsMessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js +var require_enum_object = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; + function isEnumObject(arg) { + if (typeof arg != "object" || arg === null) { + return false; + } + if (!arg.hasOwnProperty(0)) { + return false; + } + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + let nam = arg[num]; + if (nam === void 0) + return false; + if (arg[nam] !== num) + return false; + } else { + let num2 = arg[k]; + if (num2 === void 0) + return false; + if (typeof num2 !== "number") + return false; + if (arg[num2] === void 0) + return false; + } + } + return true; + } + exports2.isEnumObject = isEnumObject; + function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; + } + exports2.listEnumValues = listEnumValues; + function listEnumNames(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.name); + } + exports2.listEnumNames = listEnumNames; + function listEnumNumbers(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + } + exports2.listEnumNumbers = listEnumNumbers; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var json_typings_1 = require_json_typings(); + Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { + return json_typings_1.typeofJsonValue; + } }); + Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { + return json_typings_1.isJsonObject; + } }); + var base64_1 = require_base642(); + Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { + return base64_1.base64decode; + } }); + Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { + return base64_1.base64encode; + } }); + var protobufjs_utf8_1 = require_protobufjs_utf8(); + Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { + return protobufjs_utf8_1.utf8read; + } }); + var binary_format_contract_1 = require_binary_format_contract(); + Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { + return binary_format_contract_1.WireType; + } }); + Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { + return binary_format_contract_1.mergeBinaryOptions; + } }); + Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { + return binary_format_contract_1.UnknownFieldHandler; + } }); + var binary_reader_1 = require_binary_reader(); + Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { + return binary_reader_1.BinaryReader; + } }); + Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { + return binary_reader_1.binaryReadOptions; + } }); + var binary_writer_1 = require_binary_writer(); + Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { + return binary_writer_1.BinaryWriter; + } }); + Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { + return binary_writer_1.binaryWriteOptions; + } }); + var pb_long_1 = require_pb_long(); + Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { + return pb_long_1.PbLong; + } }); + Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { + return pb_long_1.PbULong; + } }); + var json_format_contract_1 = require_json_format_contract(); + Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonReadOptions; + } }); + Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonWriteOptions; + } }); + Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { + return json_format_contract_1.mergeJsonOptions; + } }); + var message_type_contract_1 = require_message_type_contract(); + Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { + return message_type_contract_1.MESSAGE_TYPE; + } }); + var message_type_1 = require_message_type(); + Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { + return message_type_1.MessageType; + } }); + var reflection_info_1 = require_reflection_info(); + Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { + return reflection_info_1.ScalarType; + } }); + Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { + return reflection_info_1.LongType; + } }); + Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { + return reflection_info_1.RepeatType; + } }); + Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { + return reflection_info_1.normalizeFieldInfo; + } }); + Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { + return reflection_info_1.readFieldOptions; + } }); + Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { + return reflection_info_1.readFieldOption; + } }); + Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { + return reflection_info_1.readMessageOption; + } }); + var reflection_type_check_1 = require_reflection_type_check(); + Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { + return reflection_type_check_1.ReflectionTypeCheck; + } }); + var reflection_create_1 = require_reflection_create(); + Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { + return reflection_create_1.reflectionCreate; + } }); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { + return reflection_scalar_default_1.reflectionScalarDefault; + } }); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { + return reflection_merge_partial_1.reflectionMergePartial; + } }); + var reflection_equals_1 = require_reflection_equals(); + Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { + return reflection_equals_1.reflectionEquals; + } }); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { + return reflection_binary_reader_1.ReflectionBinaryReader; + } }); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { + return reflection_binary_writer_1.ReflectionBinaryWriter; + } }); + var reflection_json_reader_1 = require_reflection_json_reader(); + Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { + return reflection_json_reader_1.ReflectionJsonReader; + } }); + var reflection_json_writer_1 = require_reflection_json_writer(); + Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { + return reflection_json_writer_1.ReflectionJsonWriter; + } }); + var reflection_contains_message_type_1 = require_reflection_contains_message_type(); + Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { + return reflection_contains_message_type_1.containsMessageType; + } }); + var oneof_1 = require_oneof(); + Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { + return oneof_1.isOneofGroup; + } }); + Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { + return oneof_1.setOneofValue; + } }); + Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { + return oneof_1.getOneofValue; + } }); + Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { + return oneof_1.clearOneofValue; + } }); + Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { + return oneof_1.getSelectedOneofValue; + } }); + var enum_object_1 = require_enum_object(); + Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { + return enum_object_1.listEnumValues; + } }); + Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { + return enum_object_1.listEnumNames; + } }); + Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { + return enum_object_1.listEnumNumbers; + } }); + Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { + return enum_object_1.isEnumObject; + } }); + var lower_camel_case_1 = require_lower_camel_case(); + Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { + return lower_camel_case_1.lowerCamelCase; + } }); + var assert_1 = require_assert(); + Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { + return assert_1.assert; + } }); + Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { + return assert_1.assertNever; + } }); + Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { + return assert_1.assertInt32; + } }); + Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { + return assert_1.assertUInt32; + } }); + Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { + return assert_1.assertFloat32; + } }); + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js +var require_reflection_info2 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + var runtime_1 = require_commonjs11(); + function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + m.serverStreaming = !!m.serverStreaming; + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + return m; + } + exports2.normalizeMethodInfo = normalizeMethodInfo; + function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readMethodOptions = readMethodOptions; + function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMethodOption = readMethodOption; + function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readServiceOption = readServiceOption; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js +var require_service_type = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServiceType = void 0; + var reflection_info_1 = require_reflection_info2(); + var ServiceType = class { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; + } + }; + exports2.ServiceType = ServiceType; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js +var require_rpc_error = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcError = void 0; + var RpcError = class extends Error { + constructor(message, code = "UNKNOWN", meta) { + super(message); + this.name = "RpcError"; + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; + } + toString() { + const l = [this.name + ": " + this.message]; + if (this.code) { + l.push(""); + l.push("Code: " + this.code); + } + if (this.serviceName && this.methodName) { + l.push("Method: " + this.serviceName + "/" + this.methodName); + } + let m = Object.entries(this.meta); + if (m.length) { + l.push(""); + l.push("Meta:"); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); + } + } + return l.join("\n"); + } + }; + exports2.RpcError = RpcError; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js +var require_rpc_options = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.mergeRpcOptions = void 0; + var runtime_1 = require_commonjs11(); + function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val2 = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); + break; + } + } + return o; + } + exports2.mergeRpcOptions = mergeRpcOptions; + function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; + } + } + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js +var require_deferred = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Deferred = exports2.DeferredState = void 0; + var DeferredState; + (function(DeferredState2) { + DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; + DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; + DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; + })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); + var Deferred = class { + /** + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. + */ + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve2, reject) => { + this._resolve = resolve2; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch((_) => { + }); + } + } + /** + * Get the current state of the promise. + */ + get state() { + return this._state; + } + /** + * Get the deferred promise. + */ + get promise() { + return this._promise; + } + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; + } + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; + } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val2) { + if (this._state === DeferredState.PENDING) + this.resolve(val2); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); + } + }; + exports2.Deferred = Deferred; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js +var require_rpc_output_stream = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcOutputStreamController = void 0; + var deferred_1 = require_deferred(); + var runtime_1 = require_commonjs11(); + var RpcOutputStreamController = class { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [] + }; + this._closed = false; + this._itState = { q: [] }; + } + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); + } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); + } + // --- Controller API + /** + * Is this stream already closed by a completion or error? + */ + get closed() { + return this._closed !== false; + } + /** + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. + */ + notifyNext(message, error2, complete) { + runtime_1.assert((message ? 1 : 0) + (error2 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); + if (message) + this.notifyMessage(message); + if (error2) + this.notifyError(error2); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. + * + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, "stream is closed"); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach((l) => l(message)); + this._lis.nxt.forEach((l) => l(message, void 0, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. + * + * Triggers onNext and onError callbacks. + */ + notifyError(error2) { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = error2; + this.pushIt(error2); + this._lis.err.forEach((l) => l(error2)); + this._lis.nxt.forEach((l) => l(void 0, error2, false)); + this.clearLis(); + } + /** + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. + */ + notifyComplete() { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach((l) => l()); + this._lis.nxt.forEach((l) => l(void 0, void 0, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); + runtime_1.assert(!state.p, "iterator contract broken"); + let first = state.q.shift(); + if (first) + return "value" in first ? Promise.resolve(first) : Promise.reject(first); + state.p = new deferred_1.Deferred(); + return state.p.promise; + } + }; + } + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (state.p) { + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + "value" in result ? p.resolve(result) : p.reject(result); + delete state.p; + } else { + state.q.push(result); + } + } + }; + exports2.RpcOutputStreamController = RpcOutputStreamController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js +var require_unary_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UnaryCall = void 0; + var UnaryCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.UnaryCall = UnaryCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js +var require_server_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerStreamingCall = void 0; + var ServerStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers + }; + }); + } + }; + exports2.ServerStreamingCall = ServerStreamingCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js +var require_client_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientStreamingCall = void 0; + var ClientStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.ClientStreamingCall = ClientStreamingCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js +var require_duplex_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DuplexStreamingCall = void 0; + var DuplexStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers + }; + }); + } + }; + exports2.DuplexStreamingCall = DuplexStreamingCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js +var require_test_transport = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TestTransport = void 0; + var rpc_error_1 = require_rpc_error(); + var runtime_1 = require_commonjs11(); + var rpc_output_stream_1 = require_rpc_output_stream(); + var rpc_options_1 = require_rpc_options(); + var unary_call_1 = require_unary_call(); + var server_streaming_call_1 = require_server_streaming_call(); + var client_streaming_call_1 = require_client_streaming_call(); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + var TestTransport = class _TestTransport { + /** + * Initialize with mock data. Omitted fields have default value. + */ + constructor(data) { + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; + } + /** + * Sent message(s) during the last operation. + */ + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; + } + /** + * Sending message(s) completed? + */ + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } else if (typeof this.lastInput == "object") { + return true; + } + return false; + } + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); + } + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } else if (this.data.response !== void 0) { + r = this.data.response; + } else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); + } + /** + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. + */ + streamResponses(method, stream, abort) { + return __awaiter4(this, void 0, void 0, function* () { + const messages = []; + if (this.data.response === void 0) { + messages.push(method.O.create()); + } else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + try { + yield delay2(this.responseDelay, abort)(void 0); + } catch (error2) { + stream.notifyError(error2); + return; + } + if (this.data.response instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.response); + return; + } + for (let msg of messages) { + stream.notifyMessage(msg); + try { + yield delay2(this.betweenResponseDelay, abort)(void 0); + } catch (error2) { + stream.notifyError(error2); + return; + } + } + if (this.data.status instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.status); + return; + } + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.trailers); + return; + } + stream.notifyComplete(); + }); + } + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); + } + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); + } + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } + } + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); + } + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); + } + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } + }; + exports2.TestTransport = TestTransport; + TestTransport.defaultHeaders = { + responseHeader: "test" + }; + TestTransport.defaultStatus = { + code: "OK", + detail: "all good" + }; + TestTransport.defaultTrailers = { + responseTrailer: "test" + }; + function delay2(ms, abort) { + return (v) => new Promise((resolve2, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } else { + const id = setTimeout(() => resolve2(v), ms); + if (abort) { + abort.addEventListener("abort", (ev) => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } + } + }); + } + var TestInputStream = class { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; + } + get sent() { + return this._sent; + } + get completed() { + return this._completed; + } + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; + return Promise.resolve(void 0).then(() => { + this._sent.push(message); + }).then(delay2(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; + return Promise.resolve(void 0).then(() => { + this._completed = true; + }).then(delay2(delayMs, this.abort)); + } + }; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js +var require_rpc_interceptor = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; + var runtime_1 = require_commonjs11(); + function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); + } + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); + } + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + } + return tail(method, options); + } + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); + } + runtime_1.assertNever(kind); + } + exports2.stackIntercept = stackIntercept; + function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); + } + exports2.stackUnaryInterceptors = stackUnaryInterceptors; + function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); + } + exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; + function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); + } + exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; + function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); + } + exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js +var require_server_call_context = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerCallContextController = void 0; + var ServerCallContextController = class { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; + } + /** + * Set the call cancelled. + * + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. + */ + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } + } + } + /** + * Send response headers. + */ + sendResponseHeaders(data) { + this._sendRH(data); + } + /** + * Is the call cancelled? + * + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. + */ + get cancelled() { + return this._cancelled; + } + /** + * Add a callback for cancellation. + */ + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; + } + }; + exports2.ServerCallContextController = ServerCallContextController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var service_type_1 = require_service_type(); + Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { + return service_type_1.ServiceType; + } }); + var reflection_info_1 = require_reflection_info2(); + Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { + return reflection_info_1.readMethodOptions; + } }); + Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { + return reflection_info_1.readMethodOption; + } }); + Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { + return reflection_info_1.readServiceOption; + } }); + var rpc_error_1 = require_rpc_error(); + Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { + return rpc_error_1.RpcError; + } }); + var rpc_options_1 = require_rpc_options(); + Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { + return rpc_options_1.mergeRpcOptions; + } }); + var rpc_output_stream_1 = require_rpc_output_stream(); + Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { + return rpc_output_stream_1.RpcOutputStreamController; + } }); + var test_transport_1 = require_test_transport(); + Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { + return test_transport_1.TestTransport; + } }); + var deferred_1 = require_deferred(); + Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { + return deferred_1.Deferred; + } }); + Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { + return deferred_1.DeferredState; + } }); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { + return duplex_streaming_call_1.DuplexStreamingCall; + } }); + var client_streaming_call_1 = require_client_streaming_call(); + Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { + return client_streaming_call_1.ClientStreamingCall; + } }); + var server_streaming_call_1 = require_server_streaming_call(); + Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { + return server_streaming_call_1.ServerStreamingCall; + } }); + var unary_call_1 = require_unary_call(); + Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { + return unary_call_1.UnaryCall; + } }); + var rpc_interceptor_1 = require_rpc_interceptor(); + Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { + return rpc_interceptor_1.stackIntercept; + } }); + Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackDuplexStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackClientStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackServerStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackUnaryInterceptors; + } }); + var server_call_context_1 = require_server_call_context(); + Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { + return server_call_context_1.ServerCallContextController; + } }); + } +}); + +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js +var require_cachescope = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheScope = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var CacheScope$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheScope", [ + { + no: 1, + name: "scope", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "permission", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + create(value) { + const message = { scope: "", permission: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string scope */ + 1: + message.scope = reader.string(); + break; + case /* int64 permission */ + 2: + message.permission = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.scope !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); + if (message.permission !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheScope = new CacheScope$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js +var require_cachemetadata = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheMetadata = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachescope_1 = require_cachescope(); + var CacheMetadata$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheMetadata", [ + { + no: 1, + name: "repository_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } + ]); + } + create(value) { + const message = { repositoryId: "0", scope: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 repository_id */ + 1: + message.repositoryId = reader.int64().toString(); + break; + case /* repeated github.actions.results.entities.v1.CacheScope scope */ + 2: + message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.repositoryId !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); + for (let i = 0; i < message.scope.length; i++) + cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheMetadata = new CacheMetadata$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js +var require_cache2 = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachemetadata_1 = require_cachemetadata(); + var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* string version */ + 3: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.version !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); + var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedUploadUrl: "", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); + var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size_bytes", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", sizeBytes: "0", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* int64 size_bytes */ + 3: + message.sizeBytes = reader.int64().toString(); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.sizeBytes !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); + var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "entry_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, entryId: "0", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* int64 entry_id */ + 2: + message.entryId = reader.int64().toString(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.entryId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); + var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "restore_keys", + kind: "scalar", + repeat: 2, + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", restoreKeys: [], version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* repeated string restore_keys */ + 3: + message.restoreKeys.push(reader.string()); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + for (let i = 0; i < message.restoreKeys.length; i++) + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); + var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_download_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "matched_key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_download_url */ + 2: + message.signedDownloadUrl = reader.string(); + break; + case /* string matched_key */ + 3: + message.matchedKey = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedDownloadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); + if (message.matchedKey !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); + exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ + { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, + { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, + { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } + ]); + } +}); + +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js +var require_cache_twirp_client = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; + var cache_1 = require_cache2(); + var CacheServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); + } + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + }; + exports2.CacheServiceClientJSON = CacheServiceClientJSON; + var CacheServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); + } + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); + } + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); + } + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); + } + }; + exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/util.js +var require_util11 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.maskSecretUrls = exports2.maskSigUrl = void 0; + var core_1 = require_core(); + function maskSigUrl(url) { + if (!url) + return; + try { + const parsedUrl = new URL(url); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); + } + } catch (error2) { + (0, core_1.debug)(`Failed to parse URL: ${url} ${error2 instanceof Error ? error2.message : String(error2)}`); + } + } + exports2.maskSigUrl = maskSigUrl; + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; + } + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); + } + if ("signed_download_url" in body && typeof body.signed_download_url === "string") { + maskSigUrl(body.signed_download_url); + } + } + exports2.maskSecretUrls = maskSecretUrls; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js +var require_cacheTwirpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.internalCacheTwirpClient = void 0; + var core_1 = require_core(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var config_1 = require_config(); + var cacheUtils_1 = require_cacheUtils(); + var auth_1 = require_auth(); + var http_client_1 = require_lib(); + var cache_twirp_client_1 = require_cache_twirp_client(); + var util_1 = require_util11(); + var CacheServiceClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, cacheUtils_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getCacheServiceURL)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) + ]); + } + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { + return __awaiter4(this, void 0, void 0, function* () { + const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url}`); + const headers = { + "Content-Type": contentType + }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url, JSON.stringify(data), headers); + })); + return body; + } catch (error2) { + throw new Error(`Failed to ${method}: ${error2.message}`); + } + }); + } + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error2) { + if (error2 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error2 instanceof errors_1.UsageError) { + throw error2; + } + if (errors_1.NetworkError.isNetworkErrorCode(error2 === null || error2 === void 0 ? void 0 : error2.code)) { + throw new errors_1.NetworkError(error2 === null || error2 === void 0 ? void 0 : error2.code); + } + isRetryable = true; + errorMessage = error2.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; + } + throw new Error(`Request failed`); + }); + } + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; + } + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); + } + sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => setTimeout(resolve2, milliseconds)); + }); + } + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); + } + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); + } + }; + function internalCacheTwirpClient(options) { + const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new cache_twirp_client_1.CacheServiceClientJSON(client); + } + exports2.internalCacheTwirpClient = internalCacheTwirpClient; + } +}); + +// node_modules/@actions/cache/lib/internal/tar.js +var require_tar = __commonJS({ + "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTar = exports2.extractTar = exports2.listTar = void 0; + var exec_1 = require_exec(); + var io4 = __importStar4(require_io()); + var fs_1 = require("fs"); + var path2 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var IS_WINDOWS = process.platform === "win32"; + function getTarPath() { + return __awaiter4(this, void 0, void 0, function* () { + switch (process.platform) { + case "win32": { + const gnuTar = yield utils.getGnuTarPathOnWindows(); + const systemTar = constants_1.SystemTarPathOnWindows; + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else if ((0, fs_1.existsSync)(systemTar)) { + return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; + } + break; + } + case "darwin": { + const gnuTar = yield io4.which("gtar", false); + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else { + return { + path: yield io4.which("tar", true), + type: constants_1.ArchiveToolType.BSD + }; + } + } + default: + break; + } + return { + path: yield io4.which("tar", true), + type: constants_1.ArchiveToolType.GNU + }; + }); + } + function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + const args = [`"${tarPath.path}"`]; + const cacheFileName = utils.getCacheFileName(compressionMethod); + const tarFile = "cache.tar"; + const workingDirectory = getWorkingDirectory(); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (type2) { + case "create": + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + break; + case "extract": + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path2.sep}`, "g"), "/")); + break; + case "list": + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P"); + break; + } + if (tarPath.type === constants_1.ArchiveToolType.GNU) { + switch (process.platform) { + case "win32": + args.push("--force-local"); + break; + case "darwin": + args.push("--delay-directory-restore"); + break; + } + } + return args; + }); + } + function getCommands(compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + let args; + const tarPath = yield getTarPath(); + const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); + const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + if (BSD_TAR_ZSTD && type2 !== "create") { + args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; + } else { + args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + } + if (BSD_TAR_ZSTD) { + return args; + } + return [args.join(" ")]; + }); + } + function getWorkingDirectory() { + var _a; + return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); + } + function getDecompressionProgram(tarPath, compressionMethod, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -d --long=30 --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/") + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -d --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/") + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + default: + return ["-z"]; + } + }); + } + function getCompressionProgram(tarPath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheFileName = utils.getCacheFileName(compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --long=30 --force -o", + cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), + constants_1.TarFilename + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --force -o", + cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), + constants_1.TarFilename + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; + default: + return ["-z"]; + } + }); + } + function execCommands(commands, cwd) { + return __awaiter4(this, void 0, void 0, function* () { + for (const command of commands) { + try { + yield (0, exec_1.exec)(command, void 0, { + cwd, + env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + }); + } catch (error2) { + throw new Error(`${command.split(" ")[0]} failed with error: ${error2 === null || error2 === void 0 ? void 0 : error2.message}`); + } + } + }); + } + function listTar(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const commands = yield getCommands(compressionMethod, "list", archivePath); + yield execCommands(commands); + }); + } + exports2.listTar = listTar; + function extractTar2(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const workingDirectory = getWorkingDirectory(); + yield io4.mkdirP(workingDirectory); + const commands = yield getCommands(compressionMethod, "extract", archivePath); + yield execCommands(commands); + }); + } + exports2.extractTar = extractTar2; + function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + (0, fs_1.writeFileSync)(path2.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + const commands = yield getCommands(compressionMethod, "create"); + yield execCommands(commands, archiveFolder); + }); + } + exports2.createTar = createTar; + } +}); + +// node_modules/@actions/cache/lib/cache.js +var require_cache3 = __commonJS({ + "node_modules/@actions/cache/lib/cache.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) 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); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__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)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + var core12 = __importStar4(require_core()); + var path2 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var cacheHttpClient = __importStar4(require_cacheHttpClient()); + var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); + var config_1 = require_config(); + var tar_1 = require_tar(); + var http_client_1 = require_lib(); + var ValidationError = class _ValidationError extends Error { + constructor(message) { + super(message); + this.name = "ValidationError"; + Object.setPrototypeOf(this, _ValidationError.prototype); + } + }; + exports2.ValidationError = ValidationError; + var ReserveCacheError = class _ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = "ReserveCacheError"; + Object.setPrototypeOf(this, _ReserveCacheError.prototype); + } + }; + exports2.ReserveCacheError = ReserveCacheError; + var FinalizeCacheError = class _FinalizeCacheError extends Error { + constructor(message) { + super(message); + this.name = "FinalizeCacheError"; + Object.setPrototypeOf(this, _FinalizeCacheError.prototype); + } + }; + exports2.FinalizeCacheError = FinalizeCacheError; + function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); + } + } + function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } + } + function isFeatureAvailable() { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + switch (cacheServiceVersion) { + case "v2": + return !!process.env["ACTIONS_RESULTS_URL"]; + case "v1": + default: + return !!process.env["ACTIONS_CACHE_URL"]; + } + } + exports2.isFeatureAvailable = isFeatureAvailable; + function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core12.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + switch (cacheServiceVersion) { + case "v2": + return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + case "v1": + default: + return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + } + }); + } + exports2.restoreCache = restoreCache3; + function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core12.debug("Resolved Keys:"); + core12.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + let archivePath = ""; + try { + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + return void 0; + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core12.info("Lookup only - skipping download"); + return cacheEntry.cacheKey; + } + archivePath = path2.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core12.debug(`Archive Path: ${archivePath}`); + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core12.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core12.info("Cache restored successfully"); + return cacheEntry.cacheKey; + } catch (error2) { + const typedError = error2; + if (typedError.name === ValidationError.name) { + throw error2; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core12.error(`Failed to restore: ${error2.message}`); + } else { + core12.warning(`Failed to restore: ${error2.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error2) { + core12.debug(`Failed to delete archive: ${error2}`); + } + } + return void 0; + }); + } + function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core12.debug("Resolved Keys:"); + core12.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + let archivePath = ""; + try { + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + const compressionMethod = yield utils.getCompressionMethod(); + const request = { + key: primaryKey, + restoreKeys, + version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) + }; + const response = yield twirpClient.GetCacheEntryDownloadURL(request); + if (!response.ok) { + core12.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); + return void 0; + } + const isRestoreKeyMatch = request.key !== response.matchedKey; + if (isRestoreKeyMatch) { + core12.info(`Cache hit for restore-key: ${response.matchedKey}`); + } else { + core12.info(`Cache hit for: ${response.matchedKey}`); + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core12.info("Lookup only - skipping download"); + return response.matchedKey; + } + archivePath = path2.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core12.debug(`Archive path: ${archivePath}`); + core12.debug(`Starting download of archive to: ${archivePath}`); + yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core12.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core12.info("Cache restored successfully"); + return response.matchedKey; + } catch (error2) { + const typedError = error2; + if (typedError.name === ValidationError.name) { + throw error2; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core12.error(`Failed to restore: ${error2.message}`); + } else { + core12.warning(`Failed to restore: ${error2.message}`); + } + } + } finally { + try { + if (archivePath) { + yield utils.unlinkFile(archivePath); + } + } catch (error2) { + core12.debug(`Failed to delete archive: ${error2}`); + } + } + return void 0; + }); + } + function saveCache3(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core12.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + checkKey(key); + switch (cacheServiceVersion) { + case "v2": + return yield saveCacheV2(paths, key, options, enableCrossOsArchive); + case "v1": + default: + return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + } + }); + } + exports2.saveCache = saveCache3; + function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { + var _a, _b, _c, _d, _e; + return __awaiter4(this, void 0, void 0, function* () { + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core12.debug("Cache Paths:"); + core12.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path2.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core12.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core12.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core12.debug("Reserving Cache"); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + enableCrossOsArchive, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + } else { + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); + } + core12.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); + } catch (error2) { + const typedError = error2; + if (typedError.name === ValidationError.name) { + throw error2; + } else if (typedError.name === ReserveCacheError.name) { + core12.info(`Failed to save: ${typedError.message}`); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core12.error(`Failed to save: ${typedError.message}`); + } else { + core12.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error2) { + core12.debug(`Failed to delete archive: ${error2}`); + } + } + return cacheId; + }); + } + function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); + const compressionMethod = yield utils.getCompressionMethod(); + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core12.debug("Cache Paths:"); + core12.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path2.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core12.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core12.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.debug(`File Size: ${archiveFileSize}`); + options.archiveSizeBytes = archiveFileSize; + core12.debug("Reserving Cache"); + const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); + const request = { + key, + version + }; + let signedUploadUrl; + try { + const response = yield twirpClient.CreateCacheEntry(request); + if (!response.ok) { + if (response.message) { + core12.warning(`Cache reservation failed: ${response.message}`); + } + throw new Error(response.message || "Response was not ok"); + } + signedUploadUrl = response.signedUploadUrl; + } catch (error2) { + core12.debug(`Failed to reserve cache: ${error2}`); + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); + } + core12.debug(`Attempting to upload cache located at: ${archivePath}`); + yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); + const finalizeRequest = { + key, + version, + sizeBytes: `${archiveFileSize}` + }; + const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); + core12.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + if (!finalizeResponse.ok) { + if (finalizeResponse.message) { + throw new FinalizeCacheError(finalizeResponse.message); + } + throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); + } + cacheId = parseInt(finalizeResponse.entryId); + } catch (error2) { + const typedError = error2; + if (typedError.name === ValidationError.name) { + throw error2; + } else if (typedError.name === ReserveCacheError.name) { + core12.info(`Failed to save: ${typedError.message}`); + } else if (typedError.name === FinalizeCacheError.name) { + core12.warning(typedError.message); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core12.error(`Failed to save: ${typedError.message}`); + } else { + core12.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error2) { + core12.debug(`Failed to delete archive: ${error2}`); + } + } + return cacheId; + }); + } + } +}); + +// src/start-proxy-action.ts +var import_child_process = require("child_process"); +var path = __toESM(require("path")); +var core11 = __toESM(require_core()); +var toolcache = __toESM(require_tool_cache()); +var import_node_forge = __toESM(require_lib2()); + +// src/actions-util.ts +var core4 = __toESM(require_core()); +var toolrunner = __toESM(require_toolrunner()); +var github = __toESM(require_github()); +var io2 = __toESM(require_io()); + +// src/util.ts +var core3 = __toESM(require_core()); +var exec = __toESM(require_exec()); +var io = __toESM(require_io()); + +// node_modules/check-disk-space/dist/check-disk-space.mjs +var import_node_child_process = require("node:child_process"); +var import_promises = require("node:fs/promises"); +var import_node_os = require("node:os"); +var import_node_path = require("node:path"); +var import_node_process = require("node:process"); +var import_node_util = require("node:util"); +var InvalidPathError = class _InvalidPathError extends Error { + constructor(message) { + super(message); + this.name = "InvalidPathError"; + Object.setPrototypeOf(this, _InvalidPathError.prototype); + } +}; +var NoMatchError = class _NoMatchError extends Error { + constructor(message) { + super(message); + this.name = "NoMatchError"; + Object.setPrototypeOf(this, _NoMatchError.prototype); + } +}; +async function isDirectoryExisting(directoryPath, dependencies) { + try { + await dependencies.fsAccess(directoryPath); + return Promise.resolve(true); + } catch (error2) { + return Promise.resolve(false); + } +} +async function getFirstExistingParentPath(directoryPath, dependencies) { + let parentDirectoryPath = directoryPath; + let parentDirectoryFound = await isDirectoryExisting(parentDirectoryPath, dependencies); + while (!parentDirectoryFound) { + parentDirectoryPath = dependencies.pathNormalize(parentDirectoryPath + "/.."); + parentDirectoryFound = await isDirectoryExisting(parentDirectoryPath, dependencies); + } + return parentDirectoryPath; +} +async function hasPowerShell3(dependencies) { + const major = parseInt(dependencies.release.split(".")[0], 10); + if (major <= 6) { + return false; + } + try { + await dependencies.cpExecFile("where", ["powershell"], { windowsHide: true }); + return true; + } catch (error2) { + return false; + } +} +function checkDiskSpace(directoryPath, dependencies = { + platform: import_node_process.platform, + release: (0, import_node_os.release)(), + fsAccess: import_promises.access, + pathNormalize: import_node_path.normalize, + pathSep: import_node_path.sep, + cpExecFile: (0, import_node_util.promisify)(import_node_child_process.execFile) +}) { + function mapOutput(stdout, filter, mapping, coefficient) { + const parsed = stdout.split("\n").map((line) => line.trim()).filter((line) => line.length !== 0).slice(1).map((line) => line.split(/\s+(?=[\d/])/)); + const filtered = parsed.filter(filter); + if (filtered.length === 0) { + throw new NoMatchError(); + } + const diskData = filtered[0]; + return { + diskPath: diskData[mapping.diskPath], + free: parseInt(diskData[mapping.free], 10) * coefficient, + size: parseInt(diskData[mapping.size], 10) * coefficient + }; + } + async function check(cmd, filter, mapping, coefficient = 1) { + const [file, ...args] = cmd; + if (file === void 0) { + return Promise.reject(new Error("cmd must contain at least one item")); + } + try { + const { stdout } = await dependencies.cpExecFile(file, args, { windowsHide: true }); + return mapOutput(stdout, filter, mapping, coefficient); + } catch (error2) { + return Promise.reject(error2); + } + } + async function checkWin32(directoryPath2) { + if (directoryPath2.charAt(1) !== ":") { + return Promise.reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath2}`)); + } + const powershellCmd = [ + "powershell", + "Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object Caption, FreeSpace, Size" + ]; + const wmicCmd = [ + "wmic", + "logicaldisk", + "get", + "size,freespace,caption" + ]; + const cmd = await hasPowerShell3(dependencies) ? powershellCmd : wmicCmd; + return check(cmd, (driveData) => { + const driveLetter = driveData[0]; + return directoryPath2.toUpperCase().startsWith(driveLetter.toUpperCase()); + }, { + diskPath: 0, + free: 1, + size: 2 + }); + } + async function checkUnix(directoryPath2) { + if (!dependencies.pathNormalize(directoryPath2).startsWith(dependencies.pathSep)) { + return Promise.reject(new InvalidPathError(`The following path is invalid (should start by ${dependencies.pathSep}): ${directoryPath2}`)); + } + const pathToCheck = await getFirstExistingParentPath(directoryPath2, dependencies); + return check( + [ + "df", + "-Pk", + "--", + pathToCheck + ], + () => true, + // We should only get one line, so we did not need to filter + { + diskPath: 5, + free: 3, + size: 1 + }, + 1024 + ); + } + if (dependencies.platform === "win32") { + return checkWin32(directoryPath); + } + return checkUnix(directoryPath); +} + +// node_modules/get-folder-size/index.js +var import_node_path2 = require("node:path"); +async function getFolderSize(itemPath, options) { + return await core(itemPath, options, { errors: true }); +} +getFolderSize.loose = async (itemPath, options) => await core(itemPath, options); +getFolderSize.strict = async (itemPath, options) => await core(itemPath, options, { strict: true }); +async function core(rootItemPath, options = {}, returnType = {}) { + const fs = options.fs || await import("node:fs/promises"); + let folderSize = 0n; + const foundInos = /* @__PURE__ */ new Set(); + const errors = []; + await processItem(rootItemPath); + async function processItem(itemPath) { + if (options.ignore?.test(itemPath)) return; + const stats = returnType.strict ? await fs.lstat(itemPath, { bigint: true }) : await fs.lstat(itemPath, { bigint: true }).catch((error2) => errors.push(error2)); + if (typeof stats !== "object") return; + if (!foundInos.has(stats.ino)) { + foundInos.add(stats.ino); + folderSize += stats.size; + } + if (stats.isDirectory()) { + const directoryItems = returnType.strict ? await fs.readdir(itemPath) : await fs.readdir(itemPath).catch((error2) => errors.push(error2)); + if (typeof directoryItems !== "object") return; + await Promise.all( + directoryItems.map( + (directoryItem) => processItem((0, import_node_path2.join)(itemPath, directoryItem)) + ) + ); + } + } + if (!options.bigint) { + if (folderSize > BigInt(Number.MAX_SAFE_INTEGER)) { + const error2 = new RangeError( + "The folder size is too large to return as a Number. You can instruct this package to return a BigInt instead." + ); + if (returnType.strict) { + throw error2; + } + errors.push(error2); + folderSize = Number.MAX_SAFE_INTEGER; + } else { + folderSize = Number(folderSize); + } + } + if (returnType.errors) { + return { + size: folderSize, + errors: errors.length > 0 ? errors : null + }; + } else { + return folderSize; + } +} + +// node_modules/js-yaml/dist/js-yaml.mjs +function isNothing(subject) { + return typeof subject === "undefined" || subject === null; +} +function isObject(subject) { + return typeof subject === "object" && subject !== null; +} +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + return [sequence]; +} +function extend(target, source) { + var index, length, key, sourceKeys; + if (source) { + sourceKeys = Object.keys(source); + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + return target; +} +function repeat(string, count) { + var result = "", cycle; + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + return result; +} +function isNegativeZero(number) { + return number === 0 && Number.NEGATIVE_INFINITY === 1 / number; +} +var isNothing_1 = isNothing; +var isObject_1 = isObject; +var toArray_1 = toArray; +var repeat_1 = repeat; +var isNegativeZero_1 = isNegativeZero; +var extend_1 = extend; +var common = { + isNothing: isNothing_1, + isObject: isObject_1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 +}; +function formatError(exception2, compact) { + var where = "", message = exception2.reason || "(unknown reason)"; + if (!exception2.mark) return message; + if (exception2.mark.name) { + where += 'in "' + exception2.mark.name + '" '; + } + where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")"; + if (!compact && exception2.mark.snippet) { + where += "\n\n" + exception2.mark.snippet; + } + return message + " " + where; +} +function YAMLException$1(reason, mark) { + Error.call(this); + this.name = "YAMLException"; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack || ""; + } +} +YAMLException$1.prototype = Object.create(Error.prototype); +YAMLException$1.prototype.constructor = YAMLException$1; +YAMLException$1.prototype.toString = function toString(compact) { + return this.name + ": " + formatError(this, compact); +}; +var exception = YAMLException$1; +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ""; + var tail = ""; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + if (position - lineStart > maxHalfLength) { + head = " ... "; + lineStart = position - maxHalfLength + head.length; + } + if (lineEnd - position > maxHalfLength) { + tail = " ..."; + lineEnd = position + maxHalfLength - tail.length; + } + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail, + pos: position - lineStart + head.length + // relative position + }; +} +function padStart(string, max) { + return common.repeat(" ", max - string.length) + string; +} +function makeSnippet(mark, options) { + options = Object.create(options || null); + if (!mark.buffer) return null; + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== "number") options.indent = 1; + if (typeof options.linesBefore !== "number") options.linesBefore = 3; + if (typeof options.linesAfter !== "number") options.linesAfter = 2; + var re = /\r?\n|\r|\0/g; + var lineStarts = [0]; + var lineEnds = []; + var match; + var foundLineNo = -1; + while (match = re.exec(mark.buffer)) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + var result = "", i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; + } + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; + result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\n"; + } + return result.replace(/\n$/, ""); +} +var snippet = makeSnippet; +var TYPE_CONSTRUCTOR_OPTIONS = [ + "kind", + "multi", + "resolve", + "construct", + "instanceOf", + "predicate", + "represent", + "representName", + "defaultStyle", + "styleAliases" +]; +var YAML_NODE_KINDS = [ + "scalar", + "sequence", + "mapping" +]; +function compileStyleAliases(map2) { + var result = {}; + if (map2 !== null) { + Object.keys(map2).forEach(function(style) { + map2[style].forEach(function(alias) { + result[String(alias)] = style; + }); + }); + } + return result; +} +function Type$1(tag, options) { + options = options || {}; + Object.keys(options).forEach(function(name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + this.options = options; + this.tag = tag; + this.kind = options["kind"] || null; + this.resolve = options["resolve"] || function() { + return true; + }; + this.construct = options["construct"] || function(data) { + return data; + }; + this.instanceOf = options["instanceOf"] || null; + this.predicate = options["predicate"] || null; + this.represent = options["represent"] || null; + this.representName = options["representName"] || null; + this.defaultStyle = options["defaultStyle"] || null; + this.multi = options["multi"] || false; + this.styleAliases = compileStyleAliases(options["styleAliases"] || null); + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} +var type = Type$1; +function compileList(schema2, name) { + var result = []; + schema2[name].forEach(function(currentType) { + var newIndex = result.length; + result.forEach(function(previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { + newIndex = previousIndex; + } + }); + result[newIndex] = currentType; + }); + return result; +} +function compileMap() { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + function collectType(type2) { + if (type2.multi) { + result.multi[type2.kind].push(type2); + result.multi["fallback"].push(type2); + } else { + result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2; + } + } + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} +function Schema$1(definition) { + return this.extend(definition); +} +Schema$1.prototype.extend = function extend2(definition) { + var implicit = []; + var explicit = []; + if (definition instanceof type) { + explicit.push(definition); + } else if (Array.isArray(definition)) { + explicit = explicit.concat(definition); + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + } else { + throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); + } + implicit.forEach(function(type$1) { + if (!(type$1 instanceof type)) { + throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); + } + if (type$1.loadKind && type$1.loadKind !== "scalar") { + throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); + } + if (type$1.multi) { + throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); + } + }); + explicit.forEach(function(type$1) { + if (!(type$1 instanceof type)) { + throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); + } + }); + var result = Object.create(Schema$1.prototype); + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + result.compiledImplicit = compileList(result, "implicit"); + result.compiledExplicit = compileList(result, "explicit"); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + return result; +}; +var schema = Schema$1; +var str = new type("tag:yaml.org,2002:str", { + kind: "scalar", + construct: function(data) { + return data !== null ? data : ""; + } +}); +var seq = new type("tag:yaml.org,2002:seq", { + kind: "sequence", + construct: function(data) { + return data !== null ? data : []; + } +}); +var map = new type("tag:yaml.org,2002:map", { + kind: "mapping", construct: function(data) { return data !== null ? data : {}; } @@ -49300,6 +94762,7 @@ var safeDump = renamed("safeDump", "dump"); // src/util.ts var semver = __toESM(require_semver2()); +var GITHUB_DOTCOM_URL = "https://github.com"; var MINIMUM_CGROUP_MEMORY_LIMIT_BYTES = 1024 * 1024; function getRequiredEnvParam(paramName) { const value = process.env[paramName]; @@ -49313,6 +94776,13 @@ var ConfigurationError = class extends Error { super(message); } }; +function isHTTPError(arg) { + return arg?.status !== void 0 && Number.isInteger(arg.status); +} +var cachedCodeQlVersion = void 0; +function getCachedCodeQlVersion() { + return cachedCodeQlVersion; +} async function delay(milliseconds, opts) { const { allowProcessExit } = opts || {}; return new Promise((resolve2) => { @@ -49322,9 +94792,80 @@ async function delay(milliseconds, opts) { } }); } +function isInTestMode() { + return process.env["CODEQL_ACTION_TEST_MODE" /* TEST_MODE */] === "true"; +} +function getTestingEnvironment() { + const testingEnvironment = process.env["CODEQL_ACTION_TESTING_ENVIRONMENT" /* TESTING_ENVIRONMENT */] || ""; + if (testingEnvironment === "") { + return void 0; + } + return testingEnvironment; +} +function wrapError(error2) { + return error2 instanceof Error ? error2 : new Error(String(error2)); +} function getErrorMessage(error2) { return error2 instanceof Error ? error2.message : String(error2); } +async function checkDiskUsage(logger) { + try { + if (process.platform === "darwin" && (process.arch === "arm" || process.arch === "arm64") && !await checkSipEnablement(logger)) { + return void 0; + } + const diskUsage = await checkDiskSpace( + getRequiredEnvParam("GITHUB_WORKSPACE") + ); + const mbInBytes = 1024 * 1024; + const gbInBytes = 1024 * 1024 * 1024; + if (diskUsage.free < 2 * gbInBytes) { + const message = `The Actions runner is running low on disk space (${(diskUsage.free / mbInBytes).toPrecision(4)} MB available).`; + if (process.env["CODEQL_ACTION_HAS_WARNED_ABOUT_DISK_SPACE" /* HAS_WARNED_ABOUT_DISK_SPACE */] !== "true") { + logger.warning(message); + } else { + logger.debug(message); + } + core3.exportVariable("CODEQL_ACTION_HAS_WARNED_ABOUT_DISK_SPACE" /* HAS_WARNED_ABOUT_DISK_SPACE */, "true"); + } + return { + numAvailableBytes: diskUsage.free, + numTotalBytes: diskUsage.size + }; + } catch (error2) { + logger.warning( + `Failed to check available disk space: ${getErrorMessage(error2)}` + ); + return void 0; + } +} +async function checkSipEnablement(logger) { + if (process.env["CODEQL_ACTION_IS_SIP_ENABLED" /* IS_SIP_ENABLED */] !== void 0 && ["true", "false"].includes(process.env["CODEQL_ACTION_IS_SIP_ENABLED" /* IS_SIP_ENABLED */])) { + return process.env["CODEQL_ACTION_IS_SIP_ENABLED" /* IS_SIP_ENABLED */] === "true"; + } + try { + const sipStatusOutput = await exec.getExecOutput("csrutil status"); + if (sipStatusOutput.exitCode === 0) { + if (sipStatusOutput.stdout.includes( + "System Integrity Protection status: enabled." + )) { + core3.exportVariable("CODEQL_ACTION_IS_SIP_ENABLED" /* IS_SIP_ENABLED */, "true"); + return true; + } + if (sipStatusOutput.stdout.includes( + "System Integrity Protection status: disabled." + )) { + core3.exportVariable("CODEQL_ACTION_IS_SIP_ENABLED" /* IS_SIP_ENABLED */, "false"); + return false; + } + } + return void 0; + } catch (e) { + logger.warning( + `Failed to determine if System Integrity Protection was enabled: ${e}` + ); + return void 0; + } +} function isDefined(value) { return value !== void 0 && value !== null; } @@ -49349,6 +94890,42 @@ function getTemporaryDirectory() { function getActionVersion() { return pkg.version; } +function getWorkflowEventName() { + return getRequiredEnvParam("GITHUB_EVENT_NAME"); +} +function getWorkflowRunID() { + const workflowRunIdString = getRequiredEnvParam("GITHUB_RUN_ID"); + const workflowRunID = parseInt(workflowRunIdString, 10); + if (Number.isNaN(workflowRunID)) { + throw new Error( + `GITHUB_RUN_ID must define a non NaN workflow run ID. Current value is ${workflowRunIdString}` + ); + } + if (workflowRunID < 0) { + throw new Error( + `GITHUB_RUN_ID must be a non-negative integer. Current value is ${workflowRunIdString}` + ); + } + return workflowRunID; +} +function getWorkflowRunAttempt() { + const workflowRunAttemptString = getRequiredEnvParam("GITHUB_RUN_ATTEMPT"); + const workflowRunAttempt = parseInt(workflowRunAttemptString, 10); + if (Number.isNaN(workflowRunAttempt)) { + throw new Error( + `GITHUB_RUN_ATTEMPT must define a non NaN workflow run attempt. Current value is ${workflowRunAttemptString}` + ); + } + if (workflowRunAttempt <= 0) { + throw new Error( + `GITHUB_RUN_ATTEMPT must be a positive integer. Current value is ${workflowRunAttemptString}` + ); + } + return workflowRunAttempt; +} +function isSelfHostedRunner() { + return process.env.RUNNER_ENVIRONMENT === "self-hosted"; +} var persistedInputsKey = "persisted_inputs"; var persistInputs = function() { const inputEnvironmentVariables = Object.entries(process.env).filter( @@ -49362,6 +94939,32 @@ var core5 = __toESM(require_core()); var githubUtils = __toESM(require_utils4()); var retry = __toESM(require_dist_node15()); var import_console_log_level = __toESM(require_console_log_level()); + +// src/repository.ts +function getRepositoryNwo() { + return getRepositoryNwoFromEnv("GITHUB_REPOSITORY"); +} +function getRepositoryNwoFromEnv(...envVarNames) { + const envVarName = envVarNames.find((name) => process.env[name]); + if (!envVarName) { + throw new ConfigurationError( + `None of the env vars ${envVarNames.join(", ")} are set` + ); + } + return parseRepositoryNwo(getRequiredEnvParam(envVarName)); +} +function parseRepositoryNwo(input) { + const parts = input.split("/"); + if (parts.length !== 2) { + throw new ConfigurationError(`"${input}" is not a valid repository name`); + } + return { + owner: parts[0], + repo: parts[1] + }; +} + +// src/api-client.ts function createApiClientWithDetails(apiDetails, { allowExternal = false } = {}) { const auth = allowExternal && apiDetails.externalRepoAuth || apiDetails.auth; const retryingOctokit = githubUtils.GitHub.plugin(retry.retry); @@ -49391,6 +94994,38 @@ function getAuthorizationHeaderFor(logger, apiDetails, url) { logger.debug(`Not using an authorization token.`); return void 0; } +async function getWorkflowRelativePath() { + const repo_nwo = getRepositoryNwo(); + const run_id = Number(getRequiredEnvParam("GITHUB_RUN_ID")); + const apiClient = getApiClient(); + const runsResponse = await apiClient.request( + "GET /repos/:owner/:repo/actions/runs/:run_id?exclude_pull_requests=true", + { + owner: repo_nwo.owner, + repo: repo_nwo.repo, + run_id + } + ); + const workflowUrl = runsResponse.data.workflow_url; + const requiredWorkflowRegex = /\/repos\/[^/]+\/[^/]+\/actions\/required_workflows\/[^/]+/; + if (!workflowUrl || requiredWorkflowRegex.test(workflowUrl)) { + return runsResponse.data.path; + } + const workflowResponse = await apiClient.request(`GET ${workflowUrl}`); + return workflowResponse.data.path; +} +async function getAnalysisKey() { + const analysisKeyEnvVar = "CODEQL_ACTION_ANALYSIS_KEY"; + let analysisKey = process.env[analysisKeyEnvVar]; + if (analysisKey !== void 0) { + return analysisKey; + } + const workflowPath = await getWorkflowRelativePath(); + const jobName = getRequiredEnvParam("GITHUB_JOB"); + analysisKey = `${workflowPath}:${jobName}`; + core5.exportVariable(analysisKeyEnvVar, analysisKey); + return analysisKey; +} // src/logging.ts var core6 = __toESM(require_core()); @@ -49402,8 +95037,8 @@ function getActionsLogger() { var core7 = __toESM(require_core()); // src/defaults.json -var bundleVersion = "codeql-bundle-v2.23.1"; -var cliVersion = "2.23.1"; +var bundleVersion = "codeql-bundle-v2.23.2"; +var cliVersion = "2.23.2"; // src/languages.ts var KnownLanguage = /* @__PURE__ */ ((KnownLanguage2) => { @@ -49517,8 +95152,8 @@ function getCredentials(logger, registrySecrets, registriesCredentials, language return out; } function getProxyPackage() { - const platform = process.platform === "win32" ? "win64" : process.platform === "darwin" ? "osx64" : "linux64"; - return `${UPDATEJOB_PROXY}-${platform}.tar.gz`; + const platform2 = process.platform === "win32" ? "win64" : process.platform === "darwin" ? "osx64" : "linux64"; + return `${UPDATEJOB_PROXY}-${platform2}.tar.gz`; } function getFallbackUrl(proxyPackage) { return `${UPDATEJOB_PROXY_URL_PREFIX}${proxyPackage}`; @@ -49562,6 +95197,514 @@ async function getDownloadUrl(logger) { }; } +// src/status-report.ts +var os = __toESM(require("os")); +var core10 = __toESM(require_core()); + +// src/analyses.ts +var AnalysisKind = /* @__PURE__ */ ((AnalysisKind2) => { + AnalysisKind2["CodeScanning"] = "code-scanning"; + AnalysisKind2["CodeQuality"] = "code-quality"; + return AnalysisKind2; +})(AnalysisKind || {}); +var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); + +// src/caching-utils.ts +var core8 = __toESM(require_core()); + +// src/config/db-config.ts +var semver2 = __toESM(require_semver2()); +var PACK_IDENTIFIER_PATTERN = (function() { + const alphaNumeric = "[a-z0-9]"; + const alphaNumericDash = "[a-z0-9-]"; + const component = `${alphaNumeric}(${alphaNumericDash}*${alphaNumeric})?`; + return new RegExp(`^${component}/${component}$`); +})(); + +// src/feature-flags.ts +var semver4 = __toESM(require_semver2()); + +// src/overlay-database-utils.ts +var actionsCache = __toESM(require_cache3()); + +// src/git-utils.ts +var core9 = __toESM(require_core()); +var toolrunner2 = __toESM(require_toolrunner()); +var io3 = __toESM(require_io()); +var runGitCommand = async function(workingDirectory, args, customErrorMessage) { + let stdout = ""; + let stderr = ""; + core9.debug(`Running git command: git ${args.join(" ")}`); + try { + await new toolrunner2.ToolRunner(await io3.which("git", true), args, { + silent: true, + listeners: { + stdout: (data) => { + stdout += data.toString(); + }, + stderr: (data) => { + stderr += data.toString(); + } + }, + cwd: workingDirectory + }).exec(); + return stdout; + } catch (error2) { + let reason = stderr; + if (stderr.includes("not a git repository")) { + reason = "The checkout path provided to the action does not appear to be a git repository."; + } + core9.info(`git call failed. ${customErrorMessage} Error: ${reason}`); + throw error2; + } +}; +var getCommitOid = async function(checkoutPath, ref = "HEAD") { + try { + const stdout = await runGitCommand( + checkoutPath, + ["rev-parse", ref], + "Continuing with commit SHA from user input or environment." + ); + return stdout.trim(); + } catch { + return getOptionalInput("sha") || getRequiredEnvParam("GITHUB_SHA"); + } +}; +function getRefFromEnv() { + let refEnv; + try { + refEnv = getRequiredEnvParam("GITHUB_REF"); + } catch (e) { + const maybeRef = process.env["CODE_SCANNING_REF"]; + if (maybeRef === void 0 || maybeRef.length === 0) { + throw e; + } + refEnv = maybeRef; + } + return refEnv; +} +async function getRef() { + const refInput = getOptionalInput("ref"); + const shaInput = getOptionalInput("sha"); + const checkoutPath = getOptionalInput("checkout_path") || getOptionalInput("source-root") || getRequiredEnvParam("GITHUB_WORKSPACE"); + const hasRefInput = !!refInput; + const hasShaInput = !!shaInput; + if ((hasRefInput || hasShaInput) && !(hasRefInput && hasShaInput)) { + throw new ConfigurationError( + "Both 'ref' and 'sha' are required if one of them is provided." + ); + } + const ref = refInput || getRefFromEnv(); + const sha = shaInput || getRequiredEnvParam("GITHUB_SHA"); + if (refInput) { + return refInput; + } + const pull_ref_regex = /refs\/pull\/(\d+)\/merge/; + if (!pull_ref_regex.test(ref)) { + return ref; + } + const head = await getCommitOid(checkoutPath, "HEAD"); + const hasChangedRef = sha !== head && await getCommitOid( + checkoutPath, + ref.replace(/^refs\/pull\//, "refs/remotes/pull/") + ) !== head; + if (hasChangedRef) { + const newRef = ref.replace(pull_ref_regex, "refs/pull/$1/head"); + core9.debug( + `No longer on merge commit, rewriting ref from ${ref} to ${newRef}.` + ); + return newRef; + } else { + return ref; + } +} + +// src/overlay-database-utils.ts +var CODEQL_OVERLAY_MINIMUM_VERSION = "2.22.4"; +var OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_MB = 15e3; +var OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_BYTES = OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_MB * 1e6; + +// src/tools-features.ts +var semver3 = __toESM(require_semver2()); + +// src/feature-flags.ts +var featureConfig = { + ["cleanup_trap_caches" /* CleanupTrapCaches */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_CLEANUP_TRAP_CACHES", + minimumVersion: void 0 + }, + ["cpp_dependency_installation_enabled" /* CppDependencyInstallation */]: { + defaultValue: false, + envVar: "CODEQL_EXTRACTOR_CPP_AUTOINSTALL_DEPENDENCIES", + legacyApi: true, + minimumVersion: "2.15.0" + }, + ["diff_informed_queries" /* DiffInformedQueries */]: { + defaultValue: true, + envVar: "CODEQL_ACTION_DIFF_INFORMED_QUERIES", + minimumVersion: "2.21.0" + }, + ["disable_csharp_buildless" /* DisableCsharpBuildless */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_DISABLE_CSHARP_BUILDLESS", + minimumVersion: void 0 + }, + ["disable_java_buildless_enabled" /* DisableJavaBuildlessEnabled */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_DISABLE_JAVA_BUILDLESS", + legacyApi: true, + minimumVersion: void 0 + }, + ["disable_kotlin_analysis_enabled" /* DisableKotlinAnalysisEnabled */]: { + defaultValue: false, + envVar: "CODEQL_DISABLE_KOTLIN_ANALYSIS", + legacyApi: true, + minimumVersion: void 0 + }, + ["export_diagnostics_enabled" /* ExportDiagnosticsEnabled */]: { + defaultValue: true, + envVar: "CODEQL_ACTION_EXPORT_DIAGNOSTICS", + legacyApi: true, + minimumVersion: void 0 + }, + ["resolve_supported_languages_using_cli" /* ResolveSupportedLanguagesUsingCli */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_RESOLVE_SUPPORTED_LANGUAGES_USING_CLI", + minimumVersion: void 0, + toolsFeature: "builtinExtractorsSpecifyDefaultQueries" /* BuiltinExtractorsSpecifyDefaultQueries */ + }, + ["overlay_analysis" /* OverlayAnalysis */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS", + minimumVersion: CODEQL_OVERLAY_MINIMUM_VERSION + }, + ["overlay_analysis_actions" /* OverlayAnalysisActions */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_ACTIONS", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_actions" /* OverlayAnalysisCodeScanningActions */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_ACTIONS", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_cpp" /* OverlayAnalysisCodeScanningCpp */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_CPP", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_csharp" /* OverlayAnalysisCodeScanningCsharp */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_CSHARP", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_go" /* OverlayAnalysisCodeScanningGo */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_GO", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_java" /* OverlayAnalysisCodeScanningJava */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_JAVA", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_javascript" /* OverlayAnalysisCodeScanningJavascript */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_JAVASCRIPT", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_python" /* OverlayAnalysisCodeScanningPython */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_PYTHON", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_ruby" /* OverlayAnalysisCodeScanningRuby */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_RUBY", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_rust" /* OverlayAnalysisCodeScanningRust */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_RUST", + minimumVersion: void 0 + }, + ["overlay_analysis_code_scanning_swift" /* OverlayAnalysisCodeScanningSwift */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CODE_SCANNING_SWIFT", + minimumVersion: void 0 + }, + ["overlay_analysis_cpp" /* OverlayAnalysisCpp */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CPP", + minimumVersion: void 0 + }, + ["overlay_analysis_csharp" /* OverlayAnalysisCsharp */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_CSHARP", + minimumVersion: void 0 + }, + ["overlay_analysis_go" /* OverlayAnalysisGo */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_GO", + minimumVersion: void 0 + }, + ["overlay_analysis_java" /* OverlayAnalysisJava */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_JAVA", + minimumVersion: void 0 + }, + ["overlay_analysis_javascript" /* OverlayAnalysisJavascript */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_JAVASCRIPT", + minimumVersion: void 0 + }, + ["overlay_analysis_python" /* OverlayAnalysisPython */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_PYTHON", + minimumVersion: void 0 + }, + ["overlay_analysis_ruby" /* OverlayAnalysisRuby */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_RUBY", + minimumVersion: void 0 + }, + ["overlay_analysis_rust" /* OverlayAnalysisRust */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_RUST", + minimumVersion: void 0 + }, + ["overlay_analysis_swift" /* OverlayAnalysisSwift */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_SWIFT", + minimumVersion: void 0 + }, + ["python_default_is_to_not_extract_stdlib" /* PythonDefaultIsToNotExtractStdlib */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_DISABLE_PYTHON_STANDARD_LIBRARY_EXTRACTION", + minimumVersion: void 0, + toolsFeature: "pythonDefaultIsToNotExtractStdlib" /* PythonDefaultIsToNotExtractStdlib */ + }, + ["use_repository_properties" /* UseRepositoryProperties */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_USE_REPOSITORY_PROPERTIES", + minimumVersion: void 0 + }, + ["qa_telemetry_enabled" /* QaTelemetryEnabled */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_QA_TELEMETRY", + legacyApi: true, + minimumVersion: void 0 + }, + ["java_minimize_dependency_jars" /* JavaMinimizeDependencyJars */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_JAVA_MINIMIZE_DEPENDENCY_JARS", + minimumVersion: "2.23.0" + } +}; + +// src/trap-caching.ts +var actionsCache2 = __toESM(require_cache3()); + +// src/config-utils.ts +var OVERLAY_ANALYSIS_FEATURES = { + actions: "overlay_analysis_actions" /* OverlayAnalysisActions */, + cpp: "overlay_analysis_cpp" /* OverlayAnalysisCpp */, + csharp: "overlay_analysis_csharp" /* OverlayAnalysisCsharp */, + go: "overlay_analysis_go" /* OverlayAnalysisGo */, + java: "overlay_analysis_java" /* OverlayAnalysisJava */, + javascript: "overlay_analysis_javascript" /* OverlayAnalysisJavascript */, + python: "overlay_analysis_python" /* OverlayAnalysisPython */, + ruby: "overlay_analysis_ruby" /* OverlayAnalysisRuby */, + rust: "overlay_analysis_rust" /* OverlayAnalysisRust */, + swift: "overlay_analysis_swift" /* OverlayAnalysisSwift */ +}; +var OVERLAY_ANALYSIS_CODE_SCANNING_FEATURES = { + actions: "overlay_analysis_code_scanning_actions" /* OverlayAnalysisCodeScanningActions */, + cpp: "overlay_analysis_code_scanning_cpp" /* OverlayAnalysisCodeScanningCpp */, + csharp: "overlay_analysis_code_scanning_csharp" /* OverlayAnalysisCodeScanningCsharp */, + go: "overlay_analysis_code_scanning_go" /* OverlayAnalysisCodeScanningGo */, + java: "overlay_analysis_code_scanning_java" /* OverlayAnalysisCodeScanningJava */, + javascript: "overlay_analysis_code_scanning_javascript" /* OverlayAnalysisCodeScanningJavascript */, + python: "overlay_analysis_code_scanning_python" /* OverlayAnalysisCodeScanningPython */, + ruby: "overlay_analysis_code_scanning_ruby" /* OverlayAnalysisCodeScanningRuby */, + rust: "overlay_analysis_code_scanning_rust" /* OverlayAnalysisCodeScanningRust */, + swift: "overlay_analysis_code_scanning_swift" /* OverlayAnalysisCodeScanningSwift */ +}; + +// src/status-report.ts +function isFirstPartyAnalysis(actionName) { + if (actionName !== "upload-sarif" /* UploadSarif */) { + return true; + } + return process.env["CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */] === "true"; +} +function getActionsStatus(error2, otherFailureCause) { + if (error2 || otherFailureCause) { + return error2 instanceof ConfigurationError ? "user-error" : "failure"; + } else { + return "success"; + } +} +function setJobStatusIfUnsuccessful(actionStatus) { + if (actionStatus === "user-error") { + core10.exportVariable( + "CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */, + process.env["CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */] ?? "JOB_STATUS_CONFIGURATION_ERROR" /* ConfigErrorStatus */ + ); + } else if (actionStatus === "failure" || actionStatus === "aborted") { + core10.exportVariable( + "CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */, + process.env["CODEQL_ACTION_JOB_STATUS" /* JOB_STATUS */] ?? "JOB_STATUS_FAILURE" /* FailureStatus */ + ); + } +} +async function createStatusReportBase(actionName, status, actionStartedAt, config, diskInfo, logger, cause, exception2) { + try { + const commitOid = getOptionalInput("sha") || process.env["GITHUB_SHA"] || ""; + const ref = await getRef(); + const jobRunUUID = process.env["JOB_RUN_UUID" /* JOB_RUN_UUID */] || ""; + const workflowRunID = getWorkflowRunID(); + const workflowRunAttempt = getWorkflowRunAttempt(); + const workflowName = process.env["GITHUB_WORKFLOW"] || ""; + const jobName = process.env["GITHUB_JOB"] || ""; + const analysis_key = await getAnalysisKey(); + let workflowStartedAt = process.env["CODEQL_WORKFLOW_STARTED_AT" /* WORKFLOW_STARTED_AT */]; + if (workflowStartedAt === void 0) { + workflowStartedAt = actionStartedAt.toISOString(); + core10.exportVariable("CODEQL_WORKFLOW_STARTED_AT" /* WORKFLOW_STARTED_AT */, workflowStartedAt); + } + const runnerOs = getRequiredEnvParam("RUNNER_OS"); + const codeQlCliVersion = getCachedCodeQlVersion(); + const actionRef = process.env["GITHUB_ACTION_REF"] || ""; + const testingEnvironment = getTestingEnvironment(); + if (testingEnvironment) { + core10.exportVariable("CODEQL_ACTION_TESTING_ENVIRONMENT" /* TESTING_ENVIRONMENT */, testingEnvironment); + } + const isSteadyStateDefaultSetupRun = process.env["CODE_SCANNING_IS_STEADY_STATE_DEFAULT_SETUP"] === "true"; + const statusReport = { + action_name: actionName, + action_oid: "unknown", + // TODO decide if it's possible to fill this in + action_ref: actionRef, + action_started_at: actionStartedAt.toISOString(), + action_version: getActionVersion(), + analysis_kinds: config?.analysisKinds.join(","), + analysis_key, + build_mode: config?.buildMode, + commit_oid: commitOid, + first_party_analysis: isFirstPartyAnalysis(actionName), + job_name: jobName, + job_run_uuid: jobRunUUID, + ref, + runner_os: runnerOs, + started_at: workflowStartedAt, + status, + steady_state_default_setup: isSteadyStateDefaultSetupRun, + testing_environment: testingEnvironment || "", + workflow_name: workflowName, + workflow_run_attempt: workflowRunAttempt, + workflow_run_id: workflowRunID + }; + try { + statusReport.actions_event_name = getWorkflowEventName(); + } catch (e) { + logger.warning(`Could not determine the workflow event name: ${e}.`); + } + if (config) { + statusReport.languages = config.languages.join(","); + } + if (diskInfo) { + statusReport.runner_available_disk_space_bytes = diskInfo.numAvailableBytes; + statusReport.runner_total_disk_space_bytes = diskInfo.numTotalBytes; + } + if (cause) { + statusReport.cause = cause; + } + if (exception2) { + statusReport.exception = exception2; + } + if (status === "success" || status === "failure" || status === "aborted" || status === "user-error") { + statusReport.completed_at = (/* @__PURE__ */ new Date()).toISOString(); + } + const matrix = getRequiredInput("matrix"); + if (matrix) { + statusReport.matrix_vars = matrix; + } + if ("RUNNER_ARCH" in process.env) { + statusReport.runner_arch = process.env["RUNNER_ARCH"]; + } + if (!(runnerOs === "Linux" && isSelfHostedRunner())) { + statusReport.runner_os_release = os.release(); + } + if (codeQlCliVersion !== void 0) { + statusReport.codeql_version = codeQlCliVersion.version; + } + const imageVersion = process.env["ImageVersion"]; + if (imageVersion) { + statusReport.runner_image_version = imageVersion; + } + return statusReport; + } catch (e) { + logger.warning( + `Caught an exception while gathering information for telemetry: ${e}. Will skip sending status report.` + ); + return void 0; + } +} +var OUT_OF_DATE_MSG = "CodeQL Action is out-of-date. Please upgrade to the latest version of codeql-action."; +var INCOMPATIBLE_MSG = "CodeQL Action version is incompatible with the code scanning endpoint. Please update to a compatible version of codeql-action."; +async function sendStatusReport(statusReport) { + setJobStatusIfUnsuccessful(statusReport.status); + const statusReportJSON = JSON.stringify(statusReport); + core10.debug(`Sending status report: ${statusReportJSON}`); + if (isInTestMode()) { + core10.debug("In test mode. Status reports are not uploaded."); + return; + } + const nwo = getRepositoryNwo(); + const client = getApiClient(); + try { + await client.request( + "PUT /repos/:owner/:repo/code-scanning/analysis/status", + { + owner: nwo.owner, + repo: nwo.repo, + data: statusReportJSON + } + ); + } catch (e) { + if (isHTTPError(e)) { + switch (e.status) { + case 403: + if (getWorkflowEventName() === "push" && process.env["GITHUB_ACTOR"] === "dependabot[bot]") { + core10.warning( + `Workflows triggered by Dependabot on the "push" event run with read-only access. Uploading Code Scanning results requires write access. To use Code Scanning with Dependabot, please ensure you are using the "pull_request" event for this workflow and avoid triggering on the "push" event for Dependabot branches. See ${"https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning#scanning-on-push" /* SCANNING_ON_PUSH */} for more information on how to configure these events.` + ); + } else { + core10.warning(e.message); + } + return; + case 404: + core10.warning(e.message); + return; + case 422: + if (getRequiredEnvParam("GITHUB_SERVER_URL") !== GITHUB_DOTCOM_URL) { + core10.debug(INCOMPATIBLE_MSG); + } else { + core10.debug(OUT_OF_DATE_MSG); + } + return; + } + } + core10.warning( + `An unexpected error occurred when sending code scanning status report: ${getErrorMessage( + e + )}` + ); + } +} + // src/start-proxy-action.ts var KEY_SIZE = 2048; var KEY_EXPIRY_YEARS = 2; @@ -49609,82 +95752,117 @@ function generateCertificateAuthority() { const key = import_node_forge.pki.privateKeyToPem(keys.privateKey); return { cert: pem, key }; } +async function sendSuccessStatusReport(startedAt, registry_types, logger) { + const statusReportBase = await createStatusReportBase( + "start-proxy" /* StartProxy */, + "success", + startedAt, + void 0, + await checkDiskUsage(logger), + logger + ); + if (statusReportBase !== void 0) { + const statusReport = { + ...statusReportBase, + registry_types: registry_types.join(",") + }; + await sendStatusReport(statusReport); + } +} async function runWrapper() { + const startedAt = /* @__PURE__ */ new Date(); persistInputs(); const logger = getActionsLogger(); - const tempDir = getTemporaryDirectory(); - const proxyLogFilePath = path.resolve(tempDir, "proxy.log"); - core8.saveState("proxy-log-file", proxyLogFilePath); - const credentials = getCredentials( - logger, - getOptionalInput("registry_secrets"), - getOptionalInput("registries_credentials"), - getOptionalInput("language") - ); - if (credentials.length === 0) { - logger.info("No credentials found, skipping proxy setup."); - return; - } - logger.info( - `Credentials loaded for the following registries: + try { + const tempDir = getTemporaryDirectory(); + const proxyLogFilePath = path.resolve(tempDir, "proxy.log"); + core11.saveState("proxy-log-file", proxyLogFilePath); + const credentials = getCredentials( + logger, + getOptionalInput("registry_secrets"), + getOptionalInput("registries_credentials"), + getOptionalInput("language") + ); + if (credentials.length === 0) { + logger.info("No credentials found, skipping proxy setup."); + return; + } + logger.info( + `Credentials loaded for the following registries: ${credentials.map((c) => credentialToStr(c)).join("\n")}` - ); - const ca = generateCertificateAuthority(); - const proxyConfig = { - all_credentials: credentials, - ca - }; - const proxyBin = await getProxyBinaryPath(logger); - await startProxy(proxyBin, proxyConfig, proxyLogFilePath, logger); + ); + const ca = generateCertificateAuthority(); + const proxyConfig = { + all_credentials: credentials, + ca + }; + const proxyBin = await getProxyBinaryPath(logger); + await startProxy(proxyBin, proxyConfig, proxyLogFilePath, logger); + await sendSuccessStatusReport( + startedAt, + proxyConfig.all_credentials.map((c) => c.type), + logger + ); + } catch (unwrappedError) { + const error2 = wrapError(unwrappedError); + core11.setFailed(`start-proxy action failed: ${error2.message}`); + const errorStatusReportBase = await createStatusReportBase( + "start-proxy" /* StartProxy */, + getActionsStatus(error2), + startedAt, + void 0, + await checkDiskUsage(logger), + logger + ); + if (errorStatusReportBase !== void 0) { + await sendStatusReport(errorStatusReportBase); + } + } } async function startProxy(binPath, config, logFilePath, logger) { const host = "127.0.0.1"; let port = 49152; - try { - let subprocess = void 0; - let tries = 5; - let subprocessError = void 0; - while (tries-- > 0 && !subprocess && !subprocessError) { - subprocess = (0, import_child_process.spawn)( - binPath, - ["-addr", `${host}:${port}`, "-config", "-", "-logfile", logFilePath], - { - detached: true, - stdio: ["pipe", "ignore", "ignore"] - } - ); - subprocess.unref(); - if (subprocess.pid) { - core8.saveState("proxy-process-pid", `${subprocess.pid}`); + let subprocess = void 0; + let tries = 5; + let subprocessError = void 0; + while (tries-- > 0 && !subprocess && !subprocessError) { + subprocess = (0, import_child_process.spawn)( + binPath, + ["-addr", `${host}:${port}`, "-config", "-", "-logfile", logFilePath], + { + detached: true, + stdio: ["pipe", "ignore", "ignore"] } - subprocess.on("error", (error2) => { - subprocessError = error2; - }); - subprocess.on("exit", (code) => { - if (code !== 0) { - port = Math.floor(Math.random() * (65535 - 49152) + 49152); - subprocess = void 0; - } - }); - subprocess.stdin?.write(JSON.stringify(config)); - subprocess.stdin?.end(); - await delay(1e3); - } - if (subprocessError) { - throw subprocessError; - } - logger.info(`Proxy started on ${host}:${port}`); - core8.setOutput("proxy_host", host); - core8.setOutput("proxy_port", port.toString()); - core8.setOutput("proxy_ca_certificate", config.ca.cert); - const registry_urls = config.all_credentials.filter((credential) => credential.url !== void 0).map((credential) => ({ - type: credential.type, - url: credential.url - })); - core8.setOutput("proxy_urls", JSON.stringify(registry_urls)); - } catch (error2) { - core8.setFailed(`start-proxy action failed: ${getErrorMessage(error2)}`); + ); + subprocess.unref(); + if (subprocess.pid) { + core11.saveState("proxy-process-pid", `${subprocess.pid}`); + } + subprocess.on("error", (error2) => { + subprocessError = error2; + }); + subprocess.on("exit", (code) => { + if (code !== 0) { + port = Math.floor(Math.random() * (65535 - 49152) + 49152); + subprocess = void 0; + } + }); + subprocess.stdin?.write(JSON.stringify(config)); + subprocess.stdin?.end(); + await delay(1e3); + } + if (subprocessError) { + throw subprocessError; } + logger.info(`Proxy started on ${host}:${port}`); + core11.setOutput("proxy_host", host); + core11.setOutput("proxy_port", port.toString()); + core11.setOutput("proxy_ca_certificate", config.ca.cert); + const registry_urls = config.all_credentials.filter((credential) => credential.url !== void 0).map((credential) => ({ + type: credential.type, + url: credential.url + })); + core11.setOutput("proxy_urls", JSON.stringify(registry_urls)); } async function getProxyBinaryPath(logger) { const proxyFileName = process.platform === "win32" ? `${UPDATEJOB_PROXY}.exe` : UPDATEJOB_PROXY; diff --git a/lib/upload-lib.js b/lib/upload-lib.js index 9d5c04e842..fb3980402d 100644 --- a/lib/upload-lib.js +++ b/lib/upload-lib.js @@ -29446,11 +29446,11 @@ var require_out = __commonJS({ async.read(path15, getSettings(optionsOrSettingsOrCallback), callback); } exports2.stat = stat; - function statSync2(path15, optionsOrSettings) { + function statSync3(path15, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path15, settings); } - exports2.statSync = statSync2; + exports2.statSync = statSync3; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; @@ -33584,7 +33584,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -35688,7 +35688,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } @@ -84821,6 +84821,7 @@ __export(upload_lib_exports, { InvalidSarifUploadError: () => InvalidSarifUploadError, buildPayload: () => buildPayload, findSarifFilesInDir: () => findSarifFilesInDir, + getGroupedSarifFilePaths: () => getGroupedSarifFilePaths, getSarifFilePaths: () => getSarifFilePaths, populateRunAutomationDetails: () => populateRunAutomationDetails, readSarifFile: () => readSarifFile, @@ -88473,6 +88474,9 @@ function getWorkflowRunAttempt() { } return workflowRunAttempt; } +function isDefaultSetup() { + return getWorkflowEventName() === "dynamic"; +} function prettyPrintInvocation(cmd, args) { return [cmd, ...args].map((x) => x.includes(" ") ? `'${x}'` : x).join(" "); } @@ -88529,6 +88533,57 @@ async function runTool(cmd, args = [], opts = {}) { } return stdout; } +var qualityCategoryMapping = { + "c#": "csharp", + cpp: "c-cpp", + c: "c-cpp", + "c++": "c-cpp", + java: "java-kotlin", + javascript: "javascript-typescript", + typescript: "javascript-typescript", + kotlin: "java-kotlin" +}; +function fixCodeQualityCategory(logger, category) { + if (category !== void 0 && isDefaultSetup() && category.startsWith("/language:")) { + const language = category.substring("/language:".length); + const mappedLanguage = qualityCategoryMapping[language]; + if (mappedLanguage) { + const newCategory = `/language:${mappedLanguage}`; + logger.info( + `Adjusted category for Code Quality from '${category}' to '${newCategory}'.` + ); + return newCategory; + } + } + return category; +} + +// src/analyses.ts +var AnalysisKind = /* @__PURE__ */ ((AnalysisKind2) => { + AnalysisKind2["CodeScanning"] = "code-scanning"; + AnalysisKind2["CodeQuality"] = "code-quality"; + return AnalysisKind2; +})(AnalysisKind || {}); +var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); +var CodeScanning = { + kind: "code-scanning" /* CodeScanning */, + name: "code scanning", + target: "PUT /repos/:owner/:repo/code-scanning/analysis" /* CODE_SCANNING */, + sarifExtension: ".sarif", + sarifPredicate: (name) => name.endsWith(CodeScanning.sarifExtension) && !CodeQuality.sarifPredicate(name), + fixCategory: (_, category) => category, + sentinelPrefix: "CODEQL_UPLOAD_SARIF_" +}; +var CodeQuality = { + kind: "code-quality" /* CodeQuality */, + name: "code quality", + target: "PUT /repos/:owner/:repo/code-quality/analysis" /* CODE_QUALITY */, + sarifExtension: ".quality.sarif", + sarifPredicate: (name) => name.endsWith(CodeQuality.sarifExtension), + fixCategory: fixCodeQualityCategory, + sentinelPrefix: "CODEQL_UPLOAD_QUALITY_SARIF_" +}; +var SarifScanOrder = [CodeQuality, CodeScanning]; // src/api-client.ts var core5 = __toESM(require_core()); @@ -88921,14 +88976,6 @@ function wrapCliConfigurationError(cliError) { var fs7 = __toESM(require("fs")); var path9 = __toESM(require("path")); -// src/analyses.ts -var AnalysisKind = /* @__PURE__ */ ((AnalysisKind2) => { - AnalysisKind2["CodeScanning"] = "code-scanning"; - AnalysisKind2["CodeQuality"] = "code-quality"; - return AnalysisKind2; -})(AnalysisKind || {}); -var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); - // src/caching-utils.ts var core6 = __toESM(require_core()); @@ -88949,8 +88996,8 @@ var path8 = __toESM(require("path")); var semver4 = __toESM(require_semver2()); // src/defaults.json -var bundleVersion = "codeql-bundle-v2.23.1"; -var cliVersion = "2.23.1"; +var bundleVersion = "codeql-bundle-v2.23.2"; +var cliVersion = "2.23.2"; // src/overlay-database-utils.ts var fs5 = __toESM(require("fs")); @@ -92391,6 +92438,54 @@ function getSarifFilePaths(sarifPath, isSarif) { } return sarifFiles; } +async function getGroupedSarifFilePaths(logger, sarifPath) { + const stats = fs13.statSync(sarifPath, { throwIfNoEntry: false }); + if (stats === void 0) { + throw new ConfigurationError(`Path does not exist: ${sarifPath}`); + } + const results = {}; + if (stats.isDirectory()) { + let unassignedSarifFiles = findSarifFilesInDir( + sarifPath, + (name) => path14.extname(name) === ".sarif" + ); + logger.debug( + `Found the following .sarif files in ${sarifPath}: ${unassignedSarifFiles.join(", ")}` + ); + for (const analysisConfig of SarifScanOrder) { + const filesForCurrentAnalysis = unassignedSarifFiles.filter( + analysisConfig.sarifPredicate + ); + if (filesForCurrentAnalysis.length > 0) { + logger.debug( + `The following SARIF files are for ${analysisConfig.name}: ${filesForCurrentAnalysis.join(", ")}` + ); + unassignedSarifFiles = unassignedSarifFiles.filter( + (name) => !analysisConfig.sarifPredicate(name) + ); + results[analysisConfig.kind] = filesForCurrentAnalysis; + } else { + logger.debug(`Found no SARIF files for ${analysisConfig.name}`); + } + } + if (unassignedSarifFiles.length !== 0) { + logger.warning( + `Found files in ${sarifPath} which do not belong to any analysis: ${unassignedSarifFiles.join(", ")}` + ); + } + } else { + for (const analysisConfig of SarifScanOrder) { + if (analysisConfig.kind === "code-scanning" /* CodeScanning */ || analysisConfig.sarifPredicate(sarifPath)) { + logger.debug( + `Using '${sarifPath}' as a SARIF file for ${analysisConfig.name}.` + ); + results[analysisConfig.kind] = [sarifPath]; + break; + } + } + } + return results; +} function countResultsInSarif(sarif) { let numResults = 0; const parsedSarif = JSON.parse(sarif); @@ -92505,6 +92600,7 @@ async function uploadSpecifiedFiles(sarifPaths, checkoutPath, category, features logger.info(`Processing sarif files: ${JSON.stringify(sarifPaths)}`); const gitHubVersion = await getGitHubVersion(); let sarif; + category = uploadTarget.fixCategory(logger, category); if (sarifPaths.length > 1) { for (const sarifPath of sarifPaths) { const parsedSarif = readSarifFile(sarifPath); @@ -92750,6 +92846,7 @@ function filterAlertsByDiffRange(logger, sarif) { InvalidSarifUploadError, buildPayload, findSarifFilesInDir, + getGroupedSarifFilePaths, getSarifFilePaths, populateRunAutomationDetails, readSarifFile, diff --git a/lib/upload-sarif-action-post.js b/lib/upload-sarif-action-post.js index 2bad6677a0..e9b083b3c3 100644 --- a/lib/upload-sarif-action-post.js +++ b/lib/upload-sarif-action-post.js @@ -26438,7 +26438,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -106366,7 +106366,7 @@ var require_brace_expansion3 = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } @@ -117619,7 +117619,7 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion if (fs.existsSync(baseTempDir)) { const outputDirs = fs.readdirSync(baseTempDir); for (const outputDir of outputDirs) { - const sarifFiles = fs.readdirSync(path.resolve(baseTempDir, outputDir)).filter((f) => f.endsWith(".sarif")); + const sarifFiles = fs.readdirSync(path.resolve(baseTempDir, outputDir)).filter((f) => path.extname(f) === ".sarif"); for (const sarifFile of sarifFiles) { toUpload.push(path.resolve(baseTempDir, outputDir, sarifFile)); } diff --git a/lib/upload-sarif-action.js b/lib/upload-sarif-action.js index 59c660b275..9efd8515be 100644 --- a/lib/upload-sarif-action.js +++ b/lib/upload-sarif-action.js @@ -185,7 +185,7 @@ var require_file_command = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.prepareKeyValueMessage = exports2.issueFileCommand = void 0; var crypto = __importStar4(require("crypto")); - var fs16 = __importStar4(require("fs")); + var fs15 = __importStar4(require("fs")); var os3 = __importStar4(require("os")); var utils_1 = require_utils(); function issueFileCommand(command, message) { @@ -193,10 +193,10 @@ var require_file_command = __commonJS({ if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } - if (!fs16.existsSync(filePath)) { + if (!fs15.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs16.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os3.EOL}`, { + fs15.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os3.EOL}`, { encoding: "utf8" }); } @@ -18513,12 +18513,12 @@ var require_io_util = __commonJS({ var _a; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getCmdPath = exports2.tryGetExecutablePath = exports2.isRooted = exports2.isDirectory = exports2.exists = exports2.READONLY = exports2.UV_FS_O_EXLOCK = exports2.IS_WINDOWS = exports2.unlink = exports2.symlink = exports2.stat = exports2.rmdir = exports2.rm = exports2.rename = exports2.readlink = exports2.readdir = exports2.open = exports2.mkdir = exports2.lstat = exports2.copyFile = exports2.chmod = void 0; - var fs16 = __importStar4(require("fs")); + var fs15 = __importStar4(require("fs")); var path16 = __importStar4(require("path")); - _a = fs16.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.readlink = _a.readlink, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; + _a = fs15.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.readlink = _a.readlink, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; exports2.IS_WINDOWS = process.platform === "win32"; exports2.UV_FS_O_EXLOCK = 268435456; - exports2.READONLY = fs16.constants.O_RDONLY; + exports2.READONLY = fs15.constants.O_RDONLY; function exists(fsPath) { return __awaiter4(this, void 0, void 0, function* () { try { @@ -27907,8 +27907,8 @@ var require_utils7 = __commonJS({ exports2.array = array; var errno = require_errno(); exports2.errno = errno; - var fs16 = require_fs(); - exports2.fs = fs16; + var fs15 = require_fs(); + exports2.fs = fs15; var path16 = require_path(); exports2.path = path16; var pattern = require_pattern(); @@ -28092,12 +28092,12 @@ var require_fs2 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createFileSystemAdapter = exports2.FILE_SYSTEM_ADAPTER = void 0; - var fs16 = require("fs"); + var fs15 = require("fs"); exports2.FILE_SYSTEM_ADAPTER = { - lstat: fs16.lstat, - stat: fs16.stat, - lstatSync: fs16.lstatSync, - statSync: fs16.statSync + lstat: fs15.lstat, + stat: fs15.stat, + lstatSync: fs15.lstatSync, + statSync: fs15.statSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === void 0) { @@ -28114,12 +28114,12 @@ var require_settings = __commonJS({ "node_modules/@nodelib/fs.stat/out/settings.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var fs16 = require_fs2(); + var fs15 = require_fs2(); var Settings = class { constructor(_options = {}) { this._options = _options; this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); - this.fs = fs16.createFileSystemAdapter(this._options.fs); + this.fs = fs15.createFileSystemAdapter(this._options.fs); this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } @@ -28149,11 +28149,11 @@ var require_out = __commonJS({ async.read(path16, getSettings(optionsOrSettingsOrCallback), callback); } exports2.stat = stat; - function statSync2(path16, optionsOrSettings) { + function statSync3(path16, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path16, settings); } - exports2.statSync = statSync2; + exports2.statSync = statSync3; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; @@ -28274,8 +28274,8 @@ var require_utils8 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.fs = void 0; - var fs16 = require_fs3(); - exports2.fs = fs16; + var fs15 = require_fs3(); + exports2.fs = fs15; } }); @@ -28470,14 +28470,14 @@ var require_fs4 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createFileSystemAdapter = exports2.FILE_SYSTEM_ADAPTER = void 0; - var fs16 = require("fs"); + var fs15 = require("fs"); exports2.FILE_SYSTEM_ADAPTER = { - lstat: fs16.lstat, - stat: fs16.stat, - lstatSync: fs16.lstatSync, - statSync: fs16.statSync, - readdir: fs16.readdir, - readdirSync: fs16.readdirSync + lstat: fs15.lstat, + stat: fs15.stat, + lstatSync: fs15.lstatSync, + statSync: fs15.statSync, + readdir: fs15.readdir, + readdirSync: fs15.readdirSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === void 0) { @@ -28496,12 +28496,12 @@ var require_settings2 = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); var path16 = require("path"); var fsStat = require_out(); - var fs16 = require_fs4(); + var fs15 = require_fs4(); var Settings = class { constructor(_options = {}) { this._options = _options; this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); - this.fs = fs16.createFileSystemAdapter(this._options.fs); + this.fs = fs15.createFileSystemAdapter(this._options.fs); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path16.sep); this.stats = this._getValue(this._options.stats, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); @@ -29762,16 +29762,16 @@ var require_settings4 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; - var fs16 = require("fs"); + var fs15 = require("fs"); var os3 = require("os"); var CPU_COUNT = Math.max(os3.cpus().length, 1); exports2.DEFAULT_FILE_SYSTEM_ADAPTER = { - lstat: fs16.lstat, - lstatSync: fs16.lstatSync, - stat: fs16.stat, - statSync: fs16.statSync, - readdir: fs16.readdir, - readdirSync: fs16.readdirSync + lstat: fs15.lstat, + lstatSync: fs15.lstatSync, + stat: fs15.stat, + statSync: fs15.statSync, + readdir: fs15.readdir, + readdirSync: fs15.readdirSync }; var Settings = class { constructor(_options = {}) { @@ -32287,7 +32287,7 @@ var require_package = __commonJS({ "package.json"(exports2, module2) { module2.exports = { name: "codeql", - version: "3.30.5", + version: "3.30.6", private: true, description: "CodeQL action", scripts: { @@ -34391,7 +34391,7 @@ var require_brace_expansion = __commonJS({ var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str2 = m.pre + "{" + m.body + escClose + m.post; return expand(str2); } @@ -35465,7 +35465,7 @@ var require_internal_globber = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DefaultGlobber = void 0; var core14 = __importStar4(require_core()); - var fs16 = __importStar4(require("fs")); + var fs15 = __importStar4(require("fs")); var globOptionsHelper = __importStar4(require_internal_glob_options_helper()); var path16 = __importStar4(require("path")); var patternHelper = __importStar4(require_internal_pattern_helper()); @@ -35517,7 +35517,7 @@ var require_internal_globber = __commonJS({ for (const searchPath of patternHelper.getSearchPaths(patterns)) { core14.debug(`Search path '${searchPath}'`); try { - yield __await4(fs16.promises.lstat(searchPath)); + yield __await4(fs15.promises.lstat(searchPath)); } catch (err) { if (err.code === "ENOENT") { continue; @@ -35548,7 +35548,7 @@ var require_internal_globber = __commonJS({ continue; } const childLevel = item.level + 1; - const childItems = (yield __await4(fs16.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path16.join(item.path, x), childLevel)); + const childItems = (yield __await4(fs15.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path16.join(item.path, x), childLevel)); stack.push(...childItems.reverse()); } else if (match & internal_match_kind_1.MatchKind.File) { yield yield __await4(item.path); @@ -35583,7 +35583,7 @@ var require_internal_globber = __commonJS({ let stats; if (options.followSymbolicLinks) { try { - stats = yield fs16.promises.stat(item.path); + stats = yield fs15.promises.stat(item.path); } catch (err) { if (err.code === "ENOENT") { if (options.omitBrokenSymbolicLinks) { @@ -35595,10 +35595,10 @@ var require_internal_globber = __commonJS({ throw err; } } else { - stats = yield fs16.promises.lstat(item.path); + stats = yield fs15.promises.lstat(item.path); } if (stats.isDirectory() && options.followSymbolicLinks) { - const realPath = yield fs16.promises.realpath(item.path); + const realPath = yield fs15.promises.realpath(item.path); while (traversalChain.length >= item.level) { traversalChain.pop(); } @@ -36932,7 +36932,7 @@ var require_cacheUtils = __commonJS({ var glob = __importStar4(require_glob()); var io6 = __importStar4(require_io()); var crypto = __importStar4(require("crypto")); - var fs16 = __importStar4(require("fs")); + var fs15 = __importStar4(require("fs")); var path16 = __importStar4(require("path")); var semver8 = __importStar4(require_semver3()); var util = __importStar4(require("util")); @@ -36962,7 +36962,7 @@ var require_cacheUtils = __commonJS({ } exports2.createTempDirectory = createTempDirectory; function getArchiveFileSizeInBytes(filePath) { - return fs16.statSync(filePath).size; + return fs15.statSync(filePath).size; } exports2.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; function resolvePaths(patterns) { @@ -37002,7 +37002,7 @@ var require_cacheUtils = __commonJS({ exports2.resolvePaths = resolvePaths; function unlinkFile(filePath) { return __awaiter4(this, void 0, void 0, function* () { - return util.promisify(fs16.unlink)(filePath); + return util.promisify(fs15.unlink)(filePath); }); } exports2.unlinkFile = unlinkFile; @@ -37047,7 +37047,7 @@ var require_cacheUtils = __commonJS({ exports2.getCacheFileName = getCacheFileName; function getGnuTarPathOnWindows() { return __awaiter4(this, void 0, void 0, function* () { - if (fs16.existsSync(constants_1.GnuTarPathOnWindows)) { + if (fs15.existsSync(constants_1.GnuTarPathOnWindows)) { return constants_1.GnuTarPathOnWindows; } const versionOutput = yield getVersion("tar"); @@ -48820,7 +48820,7 @@ var require_dist7 = __commonJS({ var stream2 = require("stream"); var coreLro = require_dist6(); var events = require("events"); - var fs16 = require("fs"); + var fs15 = require("fs"); var util = require("util"); var buffer = require("buffer"); function _interopNamespaceDefault(e) { @@ -48843,7 +48843,7 @@ var require_dist7 = __commonJS({ } var coreHttpCompat__namespace = /* @__PURE__ */ _interopNamespaceDefault(coreHttpCompat); var coreClient__namespace = /* @__PURE__ */ _interopNamespaceDefault(coreClient); - var fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs16); + var fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs15); var util__namespace = /* @__PURE__ */ _interopNamespaceDefault(util); var logger = logger$1.createClientLogger("storage-blob"); var BaseRequestPolicy = class { @@ -72691,7 +72691,7 @@ var require_downloadUtils = __commonJS({ var http_client_1 = require_lib(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); - var fs16 = __importStar4(require("fs")); + var fs15 = __importStar4(require("fs")); var stream2 = __importStar4(require("stream")); var util = __importStar4(require("util")); var utils = __importStar4(require_cacheUtils()); @@ -72802,7 +72802,7 @@ var require_downloadUtils = __commonJS({ exports2.DownloadProgress = DownloadProgress; function downloadCacheHttpClient(archiveLocation, archivePath) { return __awaiter4(this, void 0, void 0, function* () { - const writeStream = fs16.createWriteStream(archivePath); + const writeStream = fs15.createWriteStream(archivePath); const httpClient = new http_client_1.HttpClient("actions/cache"); const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter4(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); @@ -72828,7 +72828,7 @@ var require_downloadUtils = __commonJS({ function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { var _a; return __awaiter4(this, void 0, void 0, function* () { - const archiveDescriptor = yield fs16.promises.open(archivePath, "w"); + const archiveDescriptor = yield fs15.promises.open(archivePath, "w"); const httpClient = new http_client_1.HttpClient("actions/cache", void 0, { socketTimeout: options.timeoutInMs, keepAlive: true @@ -72945,7 +72945,7 @@ var require_downloadUtils = __commonJS({ } else { const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); const downloadProgress = new DownloadProgress(contentLength); - const fd = fs16.openSync(archivePath, "w"); + const fd = fs15.openSync(archivePath, "w"); try { downloadProgress.startDisplayTimer(); const controller = new abort_controller_1.AbortController(); @@ -72963,12 +72963,12 @@ var require_downloadUtils = __commonJS({ controller.abort(); throw new Error("Aborting cache download as the download time exceeded the timeout."); } else if (Buffer.isBuffer(result)) { - fs16.writeFileSync(fd, result); + fs15.writeFileSync(fd, result); } } } finally { downloadProgress.stopDisplayTimer(); - fs16.closeSync(fd); + fs15.closeSync(fd); } } }); @@ -73267,7 +73267,7 @@ var require_cacheHttpClient = __commonJS({ var core14 = __importStar4(require_core()); var http_client_1 = require_lib(); var auth_1 = require_auth(); - var fs16 = __importStar4(require("fs")); + var fs15 = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); var uploadUtils_1 = require_uploadUtils(); @@ -73405,7 +73405,7 @@ Other caches with similar key:`); return __awaiter4(this, void 0, void 0, function* () { const fileSize = utils.getArchiveFileSizeInBytes(archivePath); const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); - const fd = fs16.openSync(archivePath, "r"); + const fd = fs15.openSync(archivePath, "r"); const uploadOptions = (0, options_1.getUploadOptions)(options); const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency); const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize); @@ -73419,7 +73419,7 @@ Other caches with similar key:`); const start = offset; const end = offset + chunkSize - 1; offset += maxChunkSize; - yield uploadChunk(httpClient, resourceUrl, () => fs16.createReadStream(archivePath, { + yield uploadChunk(httpClient, resourceUrl, () => fs15.createReadStream(archivePath, { fd, start, end, @@ -73430,7 +73430,7 @@ Other caches with similar key:`); } }))); } finally { - fs16.closeSync(fd); + fs15.closeSync(fd); } return; }); @@ -80643,7 +80643,7 @@ var require_manifest = __commonJS({ var core_1 = require_core(); var os3 = require("os"); var cp = require("child_process"); - var fs16 = require("fs"); + var fs15 = require("fs"); function _findMatch(versionSpec, stable, candidates, archFilter) { return __awaiter4(this, void 0, void 0, function* () { const platFilter = os3.platform(); @@ -80707,10 +80707,10 @@ var require_manifest = __commonJS({ const lsbReleaseFile = "/etc/lsb-release"; const osReleaseFile = "/etc/os-release"; let contents = ""; - if (fs16.existsSync(lsbReleaseFile)) { - contents = fs16.readFileSync(lsbReleaseFile).toString(); - } else if (fs16.existsSync(osReleaseFile)) { - contents = fs16.readFileSync(osReleaseFile).toString(); + if (fs15.existsSync(lsbReleaseFile)) { + contents = fs15.readFileSync(lsbReleaseFile).toString(); + } else if (fs15.existsSync(osReleaseFile)) { + contents = fs15.readFileSync(osReleaseFile).toString(); } return contents; } @@ -80887,7 +80887,7 @@ var require_tool_cache = __commonJS({ var core14 = __importStar4(require_core()); var io6 = __importStar4(require_io()); var crypto = __importStar4(require("crypto")); - var fs16 = __importStar4(require("fs")); + var fs15 = __importStar4(require("fs")); var mm = __importStar4(require_manifest()); var os3 = __importStar4(require("os")); var path16 = __importStar4(require("path")); @@ -80934,7 +80934,7 @@ var require_tool_cache = __commonJS({ exports2.downloadTool = downloadTool2; function downloadToolAttempt(url2, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - if (fs16.existsSync(dest)) { + if (fs15.existsSync(dest)) { throw new Error(`Destination file path ${dest} already exists`); } const http = new httpm.HttpClient(userAgent, [], { @@ -80958,7 +80958,7 @@ var require_tool_cache = __commonJS({ const readStream = responseMessageFactory(); let succeeded = false; try { - yield pipeline(readStream, fs16.createWriteStream(dest)); + yield pipeline(readStream, fs15.createWriteStream(dest)); core14.debug("download complete"); succeeded = true; return dest; @@ -81170,11 +81170,11 @@ var require_tool_cache = __commonJS({ arch2 = arch2 || os3.arch(); core14.debug(`Caching tool ${tool} ${version} ${arch2}`); core14.debug(`source dir: ${sourceDir}`); - if (!fs16.statSync(sourceDir).isDirectory()) { + if (!fs15.statSync(sourceDir).isDirectory()) { throw new Error("sourceDir is not a directory"); } const destPath = yield _createToolPath(tool, version, arch2); - for (const itemName of fs16.readdirSync(sourceDir)) { + for (const itemName of fs15.readdirSync(sourceDir)) { const s = path16.join(sourceDir, itemName); yield io6.cp(s, destPath, { recursive: true }); } @@ -81189,7 +81189,7 @@ var require_tool_cache = __commonJS({ arch2 = arch2 || os3.arch(); core14.debug(`Caching tool ${tool} ${version} ${arch2}`); core14.debug(`source file: ${sourceFile}`); - if (!fs16.statSync(sourceFile).isFile()) { + if (!fs15.statSync(sourceFile).isFile()) { throw new Error("sourceFile is not a file"); } const destFolder = yield _createToolPath(tool, version, arch2); @@ -81219,7 +81219,7 @@ var require_tool_cache = __commonJS({ versionSpec = semver8.clean(versionSpec) || ""; const cachePath = path16.join(_getCacheDirectory(), toolName, versionSpec, arch2); core14.debug(`checking cache: ${cachePath}`); - if (fs16.existsSync(cachePath) && fs16.existsSync(`${cachePath}.complete`)) { + if (fs15.existsSync(cachePath) && fs15.existsSync(`${cachePath}.complete`)) { core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); toolPath = cachePath; } else { @@ -81233,12 +81233,12 @@ var require_tool_cache = __commonJS({ const versions = []; arch2 = arch2 || os3.arch(); const toolPath = path16.join(_getCacheDirectory(), toolName); - if (fs16.existsSync(toolPath)) { - const children = fs16.readdirSync(toolPath); + if (fs15.existsSync(toolPath)) { + const children = fs15.readdirSync(toolPath); for (const child of children) { if (isExplicitVersion(child)) { const fullPath = path16.join(toolPath, child, arch2 || ""); - if (fs16.existsSync(fullPath) && fs16.existsSync(`${fullPath}.complete`)) { + if (fs15.existsSync(fullPath) && fs15.existsSync(`${fullPath}.complete`)) { versions.push(child); } } @@ -81312,7 +81312,7 @@ var require_tool_cache = __commonJS({ function _completeToolPath(tool, version, arch2) { const folderPath = path16.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); const markerPath = `${folderPath}.complete`; - fs16.writeFileSync(markerPath, ""); + fs15.writeFileSync(markerPath, ""); core14.debug("finished caching tool"); } function isExplicitVersion(versionSpec) { @@ -84816,7 +84816,6 @@ var require_sarif_schema_2_1_0 = __commonJS({ }); // src/upload-sarif-action.ts -var fs15 = __toESM(require("fs")); var core13 = __toESM(require_core()); // src/actions-util.ts @@ -85707,21 +85706,21 @@ async function getFolderSize(itemPath, options) { getFolderSize.loose = async (itemPath, options) => await core(itemPath, options); getFolderSize.strict = async (itemPath, options) => await core(itemPath, options, { strict: true }); async function core(rootItemPath, options = {}, returnType = {}) { - const fs16 = options.fs || await import("node:fs/promises"); + const fs15 = options.fs || await import("node:fs/promises"); let folderSize = 0n; const foundInos = /* @__PURE__ */ new Set(); const errors = []; await processItem(rootItemPath); async function processItem(itemPath) { if (options.ignore?.test(itemPath)) return; - const stats = returnType.strict ? await fs16.lstat(itemPath, { bigint: true }) : await fs16.lstat(itemPath, { bigint: true }).catch((error2) => errors.push(error2)); + const stats = returnType.strict ? await fs15.lstat(itemPath, { bigint: true }) : await fs15.lstat(itemPath, { bigint: true }).catch((error2) => errors.push(error2)); if (typeof stats !== "object") return; if (!foundInos.has(stats.ino)) { foundInos.add(stats.ino); folderSize += stats.size; } if (stats.isDirectory()) { - const directoryItems = returnType.strict ? await fs16.readdir(itemPath) : await fs16.readdir(itemPath).catch((error2) => errors.push(error2)); + const directoryItems = returnType.strict ? await fs15.readdir(itemPath) : await fs15.readdir(itemPath).catch((error2) => errors.push(error2)); if (typeof directoryItems !== "object") return; await Promise.all( directoryItems.map( @@ -88591,6 +88590,11 @@ async function asyncSome(array, predicate) { const results = await Promise.all(array.map(predicate)); return results.some((result) => result); } +function unsafeEntriesInvariant(object) { + return Object.entries(object).filter( + ([_, val2]) => val2 !== void 0 + ); +} // src/actions-util.ts var pkg = require_package(); @@ -88771,6 +88775,7 @@ var CodeScanning = { target: "PUT /repos/:owner/:repo/code-scanning/analysis" /* CODE_SCANNING */, sarifExtension: ".sarif", sarifPredicate: (name) => name.endsWith(CodeScanning.sarifExtension) && !CodeQuality.sarifPredicate(name), + fixCategory: (_, category) => category, sentinelPrefix: "CODEQL_UPLOAD_SARIF_" }; var CodeQuality = { @@ -88779,8 +88784,18 @@ var CodeQuality = { target: "PUT /repos/:owner/:repo/code-quality/analysis" /* CODE_QUALITY */, sarifExtension: ".quality.sarif", sarifPredicate: (name) => name.endsWith(CodeQuality.sarifExtension), + fixCategory: fixCodeQualityCategory, sentinelPrefix: "CODEQL_UPLOAD_QUALITY_SARIF_" }; +function getAnalysisConfig(kind) { + switch (kind) { + case "code-scanning" /* CodeScanning */: + return CodeScanning; + case "code-quality" /* CodeQuality */: + return CodeQuality; + } +} +var SarifScanOrder = [CodeQuality, CodeScanning]; // src/api-client.ts var core5 = __toESM(require_core()); @@ -88932,8 +88947,8 @@ var path8 = __toESM(require("path")); var semver3 = __toESM(require_semver2()); // src/defaults.json -var bundleVersion = "codeql-bundle-v2.23.1"; -var cliVersion = "2.23.1"; +var bundleVersion = "codeql-bundle-v2.23.2"; +var cliVersion = "2.23.2"; // src/overlay-database-utils.ts var fs5 = __toESM(require("fs")); @@ -93075,6 +93090,54 @@ function findSarifFilesInDir(sarifPath, isSarif) { walkSarifFiles(sarifPath); return sarifFiles; } +async function getGroupedSarifFilePaths(logger, sarifPath) { + const stats = fs14.statSync(sarifPath, { throwIfNoEntry: false }); + if (stats === void 0) { + throw new ConfigurationError(`Path does not exist: ${sarifPath}`); + } + const results = {}; + if (stats.isDirectory()) { + let unassignedSarifFiles = findSarifFilesInDir( + sarifPath, + (name) => path15.extname(name) === ".sarif" + ); + logger.debug( + `Found the following .sarif files in ${sarifPath}: ${unassignedSarifFiles.join(", ")}` + ); + for (const analysisConfig of SarifScanOrder) { + const filesForCurrentAnalysis = unassignedSarifFiles.filter( + analysisConfig.sarifPredicate + ); + if (filesForCurrentAnalysis.length > 0) { + logger.debug( + `The following SARIF files are for ${analysisConfig.name}: ${filesForCurrentAnalysis.join(", ")}` + ); + unassignedSarifFiles = unassignedSarifFiles.filter( + (name) => !analysisConfig.sarifPredicate(name) + ); + results[analysisConfig.kind] = filesForCurrentAnalysis; + } else { + logger.debug(`Found no SARIF files for ${analysisConfig.name}`); + } + } + if (unassignedSarifFiles.length !== 0) { + logger.warning( + `Found files in ${sarifPath} which do not belong to any analysis: ${unassignedSarifFiles.join(", ")}` + ); + } + } else { + for (const analysisConfig of SarifScanOrder) { + if (analysisConfig.kind === "code-scanning" /* CodeScanning */ || analysisConfig.sarifPredicate(sarifPath)) { + logger.debug( + `Using '${sarifPath}' as a SARIF file for ${analysisConfig.name}.` + ); + results[analysisConfig.kind] = [sarifPath]; + break; + } + } + } + return results; +} function countResultsInSarif(sarif) { let numResults = 0; const parsedSarif = JSON.parse(sarif); @@ -93175,6 +93238,7 @@ async function uploadSpecifiedFiles(sarifPaths, checkoutPath, category, features logger.info(`Processing sarif files: ${JSON.stringify(sarifPaths)}`); const gitHubVersion = await getGitHubVersion(); let sarif; + category = uploadTarget.fixCategory(logger, category); if (sarifPaths.length > 1) { for (const sarifPath of sarifPaths) { const parsedSarif = readSarifFile(sarifPath); @@ -93416,31 +93480,30 @@ function filterAlertsByDiffRange(logger, sarif) { return sarif; } -// src/upload-sarif-action.ts -async function findAndUpload(logger, features, sarifPath, pathStats, checkoutPath, analysis, category) { - let sarifFiles; - if (pathStats.isDirectory()) { - sarifFiles = findSarifFilesInDir( - sarifPath, - analysis.sarifPredicate - ); - } else if (pathStats.isFile() && (analysis.sarifPredicate(sarifPath) || analysis.kind === "code-scanning" /* CodeScanning */ && !CodeQuality.sarifPredicate(sarifPath))) { - sarifFiles = [sarifPath]; - } else { - return void 0; - } - if (sarifFiles.length !== 0) { - return await uploadSpecifiedFiles( +// src/upload-sarif.ts +async function uploadSarif(logger, features, checkoutPath, sarifPath, category) { + const sarifGroups = await getGroupedSarifFilePaths( + logger, + sarifPath + ); + const uploadResults = {}; + for (const [analysisKind, sarifFiles] of unsafeEntriesInvariant( + sarifGroups + )) { + const analysisConfig = getAnalysisConfig(analysisKind); + uploadResults[analysisKind] = await uploadSpecifiedFiles( sarifFiles, checkoutPath, category, features, logger, - analysis + analysisConfig ); } - return void 0; + return uploadResults; } + +// src/upload-sarif-action.ts async function sendSuccessStatusReport(startedAt, uploadStats, logger) { const statusReportBase = await createStatusReportBase( "upload-sarif" /* UploadSarif */, @@ -93487,57 +93550,37 @@ async function run() { const sarifPath = getRequiredInput("sarif_file"); const checkoutPath = getRequiredInput("checkout_path"); const category = getOptionalInput("category"); - const pathStats = fs15.lstatSync(sarifPath, { throwIfNoEntry: false }); - if (pathStats === void 0) { - throw new ConfigurationError(`Path does not exist: ${sarifPath}.`); - } - const sarifIds = []; - const uploadResult = await findAndUpload( + const uploadResults = await uploadSarif( logger, features, - sarifPath, - pathStats, checkoutPath, - CodeScanning, + sarifPath, category ); - if (uploadResult !== void 0) { - core13.setOutput("sarif-id", uploadResult.sarifID); - sarifIds.push({ - analysis: "code-scanning" /* CodeScanning */, - id: uploadResult.sarifID - }); + if (Object.keys(uploadResults).length === 0) { + throw new ConfigurationError( + `No SARIF files found to upload in "${sarifPath}".` + ); } - const qualityUploadResult = await findAndUpload( - logger, - features, - sarifPath, - pathStats, - checkoutPath, - CodeQuality, - fixCodeQualityCategory(logger, category) - ); - if (qualityUploadResult !== void 0) { - sarifIds.push({ - analysis: "code-quality" /* CodeQuality */, - id: qualityUploadResult.sarifID - }); + const codeScanningResult = uploadResults["code-scanning" /* CodeScanning */]; + if (codeScanningResult !== void 0) { + core13.setOutput("sarif-id", codeScanningResult.sarifID); } - core13.setOutput("sarif-ids", JSON.stringify(sarifIds)); + core13.setOutput("sarif-ids", JSON.stringify(uploadResults)); if (isInTestMode()) { core13.debug("In test mode. Waiting for processing is disabled."); } else if (getRequiredInput("wait-for-processing") === "true") { - if (uploadResult !== void 0) { + if (codeScanningResult !== void 0) { await waitForProcessing( getRepositoryNwo(), - uploadResult.sarifID, + codeScanningResult.sarifID, logger ); } } await sendSuccessStatusReport( startedAt, - uploadResult?.statusReport || {}, + codeScanningResult?.statusReport || {}, logger ); } catch (unwrappedError) { diff --git a/package-lock.json b/package-lock.json index b6da79aac6..46ec821b83 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codeql", - "version": "3.30.5", + "version": "3.30.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codeql", - "version": "3.30.5", + "version": "3.30.6", "license": "MIT", "dependencies": { "@actions/artifact": "^2.3.1", @@ -4200,7 +4200,9 @@ "license": "MIT" }, "node_modules/brace-expansion": { - "version": "1.1.11", + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", diff --git a/package.json b/package.json index 89183893e8..31389bb802 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codeql", - "version": "3.30.5", + "version": "3.30.6", "private": true, "description": "CodeQL action", "scripts": { diff --git a/pr-checks/checks/upload-quality-sarif.yml b/pr-checks/checks/upload-quality-sarif.yml index cc4786735b..1d4dd9d28d 100644 --- a/pr-checks/checks/upload-quality-sarif.yml +++ b/pr-checks/checks/upload-quality-sarif.yml @@ -22,5 +22,5 @@ steps: ref: 'refs/heads/main' sha: '5e235361806c361d4d3f8859e3c897658025a9a2' - name: "Check output from `upload-sarif` step" - if: fromJSON(steps.upload-sarif.outputs.sarif-ids)[0].analysis != 'code-quality' + if: '!(fromJSON(steps.upload-sarif.outputs.sarif-ids).code-quality)' run: exit 1 diff --git a/src/analyses.ts b/src/analyses.ts index 8d8cd1d616..7cac51a345 100644 --- a/src/analyses.ts +++ b/src/analyses.ts @@ -1,3 +1,5 @@ +import { fixCodeQualityCategory } from "./actions-util"; +import { Logger } from "./logging"; import { ConfigurationError } from "./util"; export enum AnalysisKind { @@ -61,6 +63,8 @@ export interface AnalysisConfig { /** A predicate on filenames to decide whether a SARIF file * belongs to this kind of analysis. */ sarifPredicate: (name: string) => boolean; + /** Analysis-specific adjustment of the category. */ + fixCategory: (logger: Logger, category?: string) => string | undefined; /** A prefix for environment variables used to track the uniqueness of SARIF uploads. */ sentinelPrefix: string; } @@ -74,6 +78,7 @@ export const CodeScanning: AnalysisConfig = { sarifPredicate: (name) => name.endsWith(CodeScanning.sarifExtension) && !CodeQuality.sarifPredicate(name), + fixCategory: (_, category) => category, sentinelPrefix: "CODEQL_UPLOAD_SARIF_", }; @@ -84,5 +89,29 @@ export const CodeQuality: AnalysisConfig = { target: SARIF_UPLOAD_ENDPOINT.CODE_QUALITY, sarifExtension: ".quality.sarif", sarifPredicate: (name) => name.endsWith(CodeQuality.sarifExtension), + fixCategory: fixCodeQualityCategory, sentinelPrefix: "CODEQL_UPLOAD_QUALITY_SARIF_", }; + +/** + * Gets the `AnalysisConfig` corresponding to `kind`. + * @param kind The analysis kind to get the `AnalysisConfig` for. + * @returns The `AnalysisConfig` corresponding to `kind`. + */ +export function getAnalysisConfig(kind: AnalysisKind): AnalysisConfig { + // Using a switch statement here accomplishes two things: + // 1. The type checker believes us that we have a case for every `AnalysisKind`. + // 2. If we ever add another member to `AnalysisKind`, the type checker will alert us that we have to add a case. + switch (kind) { + case AnalysisKind.CodeScanning: + return CodeScanning; + case AnalysisKind.CodeQuality: + return CodeQuality; + } +} + +// Since we have overlapping extensions (i.e. ".sarif" includes ".quality.sarif"), +// we want to scan a folder containing SARIF files in an order that finds the more +// specific extensions first. This constant defines an array in the order of analyis +// configurations with more specific extensions to less specific extensions. +export const SarifScanOrder = [CodeQuality, CodeScanning]; diff --git a/src/analyze-action.ts b/src/analyze-action.ts index 31251be488..3d0fb1c89e 100644 --- a/src/analyze-action.ts +++ b/src/analyze-action.ts @@ -26,7 +26,10 @@ import { isCodeScanningEnabled, } from "./config-utils"; import { uploadDatabases } from "./database-upload"; -import { uploadDependencyCaches } from "./dependency-caching"; +import { + DependencyCacheUploadStatusReport, + uploadDependencyCaches, +} from "./dependency-caching"; import { getDiffInformedAnalysisBranches } from "./diff-informed-analysis-utils"; import { EnvVar } from "./environment"; import { Feature, Features } from "./feature-flags"; @@ -55,10 +58,15 @@ interface AnalysisStatusReport extends uploadLib.UploadStatusReport, QueriesStatusReport {} +interface DependencyCachingUploadStatusReport { + dependency_caching_upload_results?: DependencyCacheUploadStatusReport; +} + interface FinishStatusReport extends StatusReportBase, DatabaseCreationTimings, - AnalysisStatusReport {} + AnalysisStatusReport, + DependencyCachingUploadStatusReport {} interface FinishWithTrapUploadStatusReport extends FinishStatusReport { /** Size of TRAP caches that we uploaded, in bytes. */ @@ -76,6 +84,7 @@ async function sendStatusReport( dbCreationTimings: DatabaseCreationTimings | undefined, didUploadTrapCaches: boolean, trapCacheCleanup: TrapCacheCleanupStatusReport | undefined, + dependencyCacheResults: DependencyCacheUploadStatusReport | undefined, logger: Logger, ) { const status = getActionsStatus(error, stats?.analyze_failure_language); @@ -95,6 +104,7 @@ async function sendStatusReport( ...(stats || {}), ...(dbCreationTimings || {}), ...(trapCacheCleanup || {}), + dependency_caching_upload_results: dependencyCacheResults, }; if (config && didUploadTrapCaches) { const trapCacheUploadStatusReport: FinishWithTrapUploadStatusReport = { @@ -209,6 +219,7 @@ async function run() { let trapCacheUploadTime: number | undefined = undefined; let dbCreationTimings: DatabaseCreationTimings | undefined = undefined; let didUploadTrapCaches = false; + let dependencyCacheResults: DependencyCacheUploadStatusReport | undefined; util.initializeEnvironment(actionsUtil.getActionVersion()); // Make inputs accessible in the `post` step, details at @@ -345,16 +356,14 @@ async function run() { } if (isCodeQualityEnabled(config)) { + const analysis = analyses.CodeQuality; const qualityUploadResult = await uploadLib.uploadFiles( outputDir, actionsUtil.getRequiredInput("checkout_path"), - actionsUtil.fixCodeQualityCategory( - logger, - actionsUtil.getOptionalInput("category"), - ), + actionsUtil.getOptionalInput("category"), features, logger, - analyses.CodeQuality, + analysis, ); core.setOutput("quality-sarif-id", qualityUploadResult.sarifID); } @@ -388,7 +397,11 @@ async function run() { Feature.JavaMinimizeDependencyJars, codeql, ); - await uploadDependencyCaches(config, logger, minimizeJavaJars); + dependencyCacheResults = await uploadDependencyCaches( + config, + logger, + minimizeJavaJars, + ); } // We don't upload results in test mode, so don't wait for processing @@ -431,6 +444,7 @@ async function run() { dbCreationTimings, didUploadTrapCaches, trapCacheCleanupTelemetry, + dependencyCacheResults, logger, ); return; @@ -449,6 +463,7 @@ async function run() { dbCreationTimings, didUploadTrapCaches, trapCacheCleanupTelemetry, + dependencyCacheResults, logger, ); } else if (runStats) { @@ -461,6 +476,7 @@ async function run() { dbCreationTimings, didUploadTrapCaches, trapCacheCleanupTelemetry, + dependencyCacheResults, logger, ); } else { @@ -473,6 +489,7 @@ async function run() { dbCreationTimings, didUploadTrapCaches, trapCacheCleanupTelemetry, + dependencyCacheResults, logger, ); } diff --git a/src/analyze.test.ts b/src/analyze.test.ts index 305d41d241..f3d516a78a 100644 --- a/src/analyze.test.ts +++ b/src/analyze.test.ts @@ -334,7 +334,7 @@ test("resolveQuerySuiteAlias", (t) => { for (const suite of defaultSuites) { const resolved = resolveQuerySuiteAlias(KnownLanguage.go, suite); t.assert( - resolved.endsWith(".qls"), + path.extname(resolved) === ".qls", "Resolved default suite doesn't end in .qls", ); t.assert( diff --git a/src/analyze.ts b/src/analyze.ts index b22e9c23da..b7eec921ac 100644 --- a/src/analyze.ts +++ b/src/analyze.ts @@ -7,7 +7,6 @@ import * as del from "del"; import * as yaml from "js-yaml"; import { - fixCodeQualityCategory, getRequiredInput, getTemporaryDirectory, PullRequestBranches, @@ -781,7 +780,7 @@ export async function runQueries( // accepted by the Code Quality backend. let category = automationDetailsId; if (analysis.kind === analyses.AnalysisKind.CodeQuality) { - category = fixCodeQualityCategory(logger, automationDetailsId); + category = analysis.fixCategory(logger, automationDetailsId); } const sarifFile = path.join( diff --git a/src/api-client.ts b/src/api-client.ts index 86134b7f89..153712c7fe 100644 --- a/src/api-client.ts +++ b/src/api-client.ts @@ -245,7 +245,7 @@ export interface ActionsCacheItem { /** List all Actions cache entries matching the provided key and ref. */ export async function listActionsCaches( key: string, - ref: string, + ref?: string, ): Promise { const repositoryNwo = getRepositoryNwo(); diff --git a/src/config/db-config.test.ts b/src/config/db-config.test.ts index b22503475d..533459de24 100644 --- a/src/config/db-config.test.ts +++ b/src/config/db-config.test.ts @@ -153,7 +153,6 @@ const packSpecPrettyPrintingMacro = test.macro({ title: ( _providedTitle: string | undefined, packStr: string, - // eslint-disable-next-line @typescript-eslint/no-unused-vars _packObj: dbConfig.Pack, ) => `Prettyprint pack spec: '${packStr}'`, }); diff --git a/src/debug-artifacts.ts b/src/debug-artifacts.ts index a355341d04..90e493d680 100644 --- a/src/debug-artifacts.ts +++ b/src/debug-artifacts.ts @@ -59,7 +59,7 @@ export async function uploadCombinedSarifArtifacts( for (const outputDir of outputDirs) { const sarifFiles = fs .readdirSync(path.resolve(baseTempDir, outputDir)) - .filter((f) => f.endsWith(".sarif")); + .filter((f) => path.extname(f) === ".sarif"); for (const sarifFile of sarifFiles) { toUpload.push(path.resolve(baseTempDir, outputDir, sarifFile)); diff --git a/src/defaults.json b/src/defaults.json index dbc0d5e258..3c4a3ddbef 100644 --- a/src/defaults.json +++ b/src/defaults.json @@ -1,6 +1,6 @@ { - "bundleVersion": "codeql-bundle-v2.23.1", - "cliVersion": "2.23.1", - "priorBundleVersion": "codeql-bundle-v2.23.0", - "priorCliVersion": "2.23.0" + "bundleVersion": "codeql-bundle-v2.23.2", + "cliVersion": "2.23.2", + "priorBundleVersion": "codeql-bundle-v2.23.1", + "priorCliVersion": "2.23.1" } diff --git a/src/dependency-caching.ts b/src/dependency-caching.ts index 6289ca2f68..5c7a4a4e88 100644 --- a/src/dependency-caching.ts +++ b/src/dependency-caching.ts @@ -5,12 +5,13 @@ import * as actionsCache from "@actions/cache"; import * as glob from "@actions/glob"; import { getTemporaryDirectory } from "./actions-util"; +import { listActionsCaches } from "./api-client"; import { getTotalCacheSize } from "./caching-utils"; import { Config } from "./config-utils"; import { EnvVar } from "./environment"; import { KnownLanguage, Language } from "./languages"; import { Logger } from "./logging"; -import { getRequiredEnvParam } from "./util"; +import { getErrorMessage, getRequiredEnvParam } from "./util"; /** * Caching configuration for a particular language. @@ -84,20 +85,42 @@ async function makeGlobber(patterns: string[]): Promise { return glob.create(patterns.join("\n")); } +/** Enumerates possible outcomes for cache hits. */ +export enum CacheHitKind { + /** We were unable to calculate a hash for the key. */ + NoHash = "no-hash", + /** No cache was found. */ + Miss = "miss", + /** The primary cache key matched. */ + Exact = "exact", + /** A restore key matched. */ + Partial = "partial", +} + +/** Represents results of trying to restore a dependency cache for a language. */ +export interface DependencyCacheRestoreStatus { + language: Language; + hit_kind: CacheHitKind; + download_duration_ms?: number; +} + +/** An array of `DependencyCacheRestoreStatus` objects for each analysed language with a caching configuration. */ +export type DependencyCacheRestoreStatusReport = DependencyCacheRestoreStatus[]; + /** * Attempts to restore dependency caches for the languages being analyzed. * * @param languages The languages being analyzed. * @param logger A logger to record some informational messages to. * @param minimizeJavaJars Whether the Java extractor should rewrite downloaded JARs to minimize their size. - * @returns A list of languages for which dependency caches were restored. + * @returns An array of `DependencyCacheRestoreStatus` objects for each analysed language with a caching configuration. */ export async function downloadDependencyCaches( languages: Language[], logger: Logger, minimizeJavaJars: boolean, -): Promise { - const restoredCaches: Language[] = []; +): Promise { + const status: DependencyCacheRestoreStatusReport = []; for (const language of languages) { const cacheConfig = getDefaultCacheConfig()[language]; @@ -114,6 +137,7 @@ export async function downloadDependencyCaches( const globber = await makeGlobber(cacheConfig.hash); if ((await globber.glob()).length === 0) { + status.push({ language, hit_kind: CacheHitKind.NoHash }); logger.info( `Skipping download of dependency cache for ${language} as we cannot calculate a hash for the cache key.`, ); @@ -131,35 +155,66 @@ export async function downloadDependencyCaches( )}`, ); + const start = performance.now(); const hitKey = await actionsCache.restoreCache( cacheConfig.paths, primaryKey, restoreKeys, ); + const download_duration_ms = Math.round(performance.now() - start); if (hitKey !== undefined) { logger.info(`Cache hit on key ${hitKey} for ${language}.`); - restoredCaches.push(language); + const hit_kind = + hitKey === primaryKey ? CacheHitKind.Exact : CacheHitKind.Partial; + status.push({ language, hit_kind, download_duration_ms }); } else { + status.push({ language, hit_kind: CacheHitKind.Miss }); logger.info(`No suitable cache found for ${language}.`); } } - return restoredCaches; + return status; +} + +/** Enumerates possible outcomes for storing caches. */ +export enum CacheStoreResult { + /** We were unable to calculate a hash for the key. */ + NoHash = "no-hash", + /** There is nothing to store in the cache. */ + Empty = "empty", + /** There already exists a cache with the key we are trying to store. */ + Duplicate = "duplicate", + /** The cache was stored successfully. */ + Stored = "stored", } +/** Represents results of trying to upload a dependency cache for a language. */ +export interface DependencyCacheUploadStatus { + language: Language; + result: CacheStoreResult; + upload_size_bytes?: number; + upload_duration_ms?: number; +} + +/** An array of `DependencyCacheUploadStatus` objects for each analysed language with a caching configuration. */ +export type DependencyCacheUploadStatusReport = DependencyCacheUploadStatus[]; + /** * Attempts to store caches for the languages that were analyzed. * * @param config The configuration for this workflow. * @param logger A logger to record some informational messages to. * @param minimizeJavaJars Whether the Java extractor should rewrite downloaded JARs to minimize their size. + * + * @returns An array of `DependencyCacheUploadStatus` objects for each analysed language with a caching configuration. */ export async function uploadDependencyCaches( config: Config, logger: Logger, minimizeJavaJars: boolean, -): Promise { +): Promise { + const status: DependencyCacheUploadStatusReport = []; for (const language of config.languages) { const cacheConfig = getDefaultCacheConfig()[language]; @@ -175,6 +230,7 @@ export async function uploadDependencyCaches( const globber = await makeGlobber(cacheConfig.hash); if ((await globber.glob()).length === 0) { + status.push({ language, result: CacheStoreResult.NoHash }); logger.info( `Skipping upload of dependency cache for ${language} as we cannot calculate a hash for the cache key.`, ); @@ -195,6 +251,7 @@ export async function uploadDependencyCaches( // Skip uploading an empty cache. if (size === 0) { + status.push({ language, result: CacheStoreResult.Empty }); logger.info( `Skipping upload of dependency cache for ${language} since it is empty.`, ); @@ -208,7 +265,16 @@ export async function uploadDependencyCaches( ); try { + const start = performance.now(); await actionsCache.saveCache(cacheConfig.paths, key); + const upload_duration_ms = Math.round(performance.now() - start); + + status.push({ + language, + result: CacheStoreResult.Stored, + upload_size_bytes: Math.round(size), + upload_duration_ms, + }); } catch (error) { // `ReserveCacheError` indicates that the cache key is already in use, which means that a // cache with that key already exists or is in the process of being uploaded by another @@ -218,12 +284,16 @@ export async function uploadDependencyCaches( `Not uploading cache for ${language}, because ${key} is already in use.`, ); logger.debug(error.message); + + status.push({ language, result: CacheStoreResult.Duplicate }); } else { // Propagate other errors upwards. throw error; } } } + + return status; } /** @@ -270,3 +340,34 @@ async function cachePrefix( return `${prefix}-${CODEQL_DEPENDENCY_CACHE_VERSION}-${runnerOs}-${language}-`; } + +/** Represents information about our overall cache usage for CodeQL dependency caches. */ +export interface DependencyCachingUsageReport { + count: number; + size_bytes: number; +} + +/** + * Tries to determine the overall cache usage for CodeQL dependencies caches. + * + * @param logger The logger to log errors to. + * @returns Returns the overall cache usage for CodeQL dependencies caches, or `undefined` if we couldn't determine it. + */ +export async function getDependencyCacheUsage( + logger: Logger, +): Promise { + try { + const caches = await listActionsCaches(CODEQL_DEPENDENCY_CACHE_PREFIX); + const totalSize = caches.reduce( + (acc, cache) => acc + (cache.size_in_bytes ?? 0), + 0, + ); + return { count: caches.length, size_bytes: totalSize }; + } catch (err) { + logger.warning( + `Unable to retrieve information about dependency cache usage: ${getErrorMessage(err)}`, + ); + } + + return undefined; +} diff --git a/src/init-action-post-helper.ts b/src/init-action-post-helper.ts index 0d21bd3b66..97bf21adac 100644 --- a/src/init-action-post-helper.ts +++ b/src/init-action-post-helper.ts @@ -8,6 +8,7 @@ import { CodeScanning } from "./analyses"; import { getApiClient } from "./api-client"; import { CodeQL, getCodeQL } from "./codeql"; import { Config } from "./config-utils"; +import * as dependencyCaching from "./dependency-caching"; import { EnvVar } from "./environment"; import { Feature, FeatureEnablement } from "./feature-flags"; import { Logger } from "./logging"; @@ -45,6 +46,10 @@ export interface JobStatusReport { job_status: JobStatus; } +export interface DependencyCachingUsageReport { + dependency_caching_usage?: dependencyCaching.DependencyCachingUsageReport; +} + function createFailedUploadFailedSarifResult( error: unknown, ): UploadFailedSarifResult { diff --git a/src/init-action-post.ts b/src/init-action-post.ts index b7c0e92a4d..9a93f38bc7 100644 --- a/src/init-action-post.ts +++ b/src/init-action-post.ts @@ -12,10 +12,16 @@ import { printDebugLogs, } from "./actions-util"; import { getGitHubVersion } from "./api-client"; +import { CachingKind } from "./caching-utils"; import { getCodeQL } from "./codeql"; import { Config, getConfig } from "./config-utils"; import * as debugArtifacts from "./debug-artifacts"; +import { + DependencyCachingUsageReport, + getDependencyCacheUsage, +} from "./dependency-caching"; import { Features } from "./feature-flags"; +import * as gitUtils from "./git-utils"; import * as initActionPostHelper from "./init-action-post-helper"; import { getActionsLogger } from "./logging"; import { getRepositoryNwo } from "./repository"; @@ -32,7 +38,8 @@ import { checkDiskUsage, checkGitHubVersionInRange, wrapError } from "./util"; interface InitPostStatusReport extends StatusReportBase, initActionPostHelper.UploadFailedSarifResult, - initActionPostHelper.JobStatusReport {} + initActionPostHelper.JobStatusReport, + initActionPostHelper.DependencyCachingUsageReport {} async function runWrapper() { const logger = getActionsLogger(); @@ -41,6 +48,7 @@ async function runWrapper() { let uploadFailedSarifResult: | initActionPostHelper.UploadFailedSarifResult | undefined; + let dependencyCachingUsage: DependencyCachingUsageReport | undefined; try { // Restore inputs from `init` Action. restoreInputs(); @@ -73,6 +81,17 @@ async function runWrapper() { features, logger, ); + + // If we are analysing the default branch and some kind of caching is enabled, + // then try to determine our overall cache usage for dependency caches. We only + // do this under these circumstances to avoid slowing down analyses for PRs + // and where caching may not be enabled. + if ( + (await gitUtils.isAnalyzingDefaultBranch()) && + config.dependencyCachingEnabled !== CachingKind.None + ) { + dependencyCachingUsage = await getDependencyCacheUsage(logger); + } } } catch (unwrappedError) { const error = wrapError(unwrappedError); @@ -109,6 +128,7 @@ async function runWrapper() { ...statusReportBase, ...uploadFailedSarifResult, job_status: initActionPostHelper.getFinalJobStatus(), + dependency_caching_usage: dependencyCachingUsage, }; logger.info("Sending status report for init-post step."); await sendStatusReport(statusReport); diff --git a/src/init-action.ts b/src/init-action.ts index 2b4dba3fcf..114ad6cab1 100644 --- a/src/init-action.ts +++ b/src/init-action.ts @@ -23,7 +23,10 @@ import { } from "./caching-utils"; import { CodeQL } from "./codeql"; import * as configUtils from "./config-utils"; -import { downloadDependencyCaches } from "./dependency-caching"; +import { + DependencyCacheRestoreStatusReport, + downloadDependencyCaches, +} from "./dependency-caching"; import { addDiagnostic, flushDiagnostics, @@ -102,6 +105,7 @@ async function sendCompletedStatusReport( toolsSource: ToolsSource, toolsVersion: string, overlayBaseDatabaseStats: OverlayBaseDatabaseDownloadStats | undefined, + dependencyCachingResults: DependencyCacheRestoreStatusReport | undefined, logger: Logger, error?: Error, ) { @@ -151,6 +155,7 @@ async function sendCompletedStatusReport( await getTotalCacheSize(Object.values(config.trapCaches), logger), ), overlayBaseDatabaseStats, + dependencyCachingResults, ); await sendStatusReport({ ...initWithConfigStatusReport, @@ -351,6 +356,7 @@ async function run() { } let overlayBaseDatabaseStats: OverlayBaseDatabaseDownloadStats | undefined; + let dependencyCachingResults: DependencyCacheRestoreStatusReport | undefined; try { if ( config.overlayDatabaseMode === OverlayDatabaseMode.Overlay && @@ -562,7 +568,7 @@ async function run() { codeql, ); if (shouldRestoreCache(config.dependencyCachingEnabled)) { - await downloadDependencyCaches( + dependencyCachingResults = await downloadDependencyCaches( config.languages, logger, minimizeJavaJars, @@ -714,6 +720,7 @@ async function run() { toolsSource, toolsVersion, overlayBaseDatabaseStats, + dependencyCachingResults, logger, error, ); @@ -736,6 +743,7 @@ async function run() { toolsSource, toolsVersion, overlayBaseDatabaseStats, + dependencyCachingResults, logger, ); } diff --git a/src/start-proxy-action.ts b/src/start-proxy-action.ts index 9592b904bb..966c954b44 100644 --- a/src/start-proxy-action.ts +++ b/src/start-proxy-action.ts @@ -14,6 +14,13 @@ import { getDownloadUrl, UPDATEJOB_PROXY, } from "./start-proxy"; +import { + ActionName, + createStatusReportBase, + getActionsStatus, + sendStatusReport, + StatusReportBase, +} from "./status-report"; import * as util from "./util"; const KEY_SIZE = 2048; @@ -83,46 +90,102 @@ function generateCertificateAuthority(): CertificateAuthority { return { cert: pem, key }; } +interface StartProxyStatus extends StatusReportBase { + // A comma-separated list of registry types which are configured for CodeQL. + // This only includes registry types we support, not all that are configured. + registry_types: string; +} + +async function sendSuccessStatusReport( + startedAt: Date, + registry_types: string[], + logger: Logger, +) { + const statusReportBase = await createStatusReportBase( + ActionName.StartProxy, + "success", + startedAt, + undefined, + await util.checkDiskUsage(logger), + logger, + ); + if (statusReportBase !== undefined) { + const statusReport: StartProxyStatus = { + ...statusReportBase, + registry_types: registry_types.join(","), + }; + await sendStatusReport(statusReport); + } +} + async function runWrapper() { + const startedAt = new Date(); + // Make inputs accessible in the `post` step. actionsUtil.persistInputs(); const logger = getActionsLogger(); - // Setup logging for the proxy - const tempDir = actionsUtil.getTemporaryDirectory(); - const proxyLogFilePath = path.resolve(tempDir, "proxy.log"); - core.saveState("proxy-log-file", proxyLogFilePath); + try { + // Setup logging for the proxy + const tempDir = actionsUtil.getTemporaryDirectory(); + const proxyLogFilePath = path.resolve(tempDir, "proxy.log"); + core.saveState("proxy-log-file", proxyLogFilePath); - // Get the configuration options - const credentials = getCredentials( - logger, - actionsUtil.getOptionalInput("registry_secrets"), - actionsUtil.getOptionalInput("registries_credentials"), - actionsUtil.getOptionalInput("language"), - ); + // Get the configuration options + const credentials = getCredentials( + logger, + actionsUtil.getOptionalInput("registry_secrets"), + actionsUtil.getOptionalInput("registries_credentials"), + actionsUtil.getOptionalInput("language"), + ); - if (credentials.length === 0) { - logger.info("No credentials found, skipping proxy setup."); - return; - } + if (credentials.length === 0) { + logger.info("No credentials found, skipping proxy setup."); + return; + } - logger.info( - `Credentials loaded for the following registries:\n ${credentials - .map((c) => credentialToStr(c)) - .join("\n")}`, - ); + logger.info( + `Credentials loaded for the following registries:\n ${credentials + .map((c) => credentialToStr(c)) + .join("\n")}`, + ); + + const ca = generateCertificateAuthority(); + + const proxyConfig: ProxyConfig = { + all_credentials: credentials, + ca, + }; - const ca = generateCertificateAuthority(); + // Start the Proxy + const proxyBin = await getProxyBinaryPath(logger); + await startProxy(proxyBin, proxyConfig, proxyLogFilePath, logger); - const proxyConfig: ProxyConfig = { - all_credentials: credentials, - ca, - }; + // Report success if we have reached this point. + await sendSuccessStatusReport( + startedAt, + proxyConfig.all_credentials.map((c) => c.type), + logger, + ); + } catch (unwrappedError) { + const error = util.wrapError(unwrappedError); + core.setFailed(`start-proxy action failed: ${error.message}`); - // Start the Proxy - const proxyBin = await getProxyBinaryPath(logger); - await startProxy(proxyBin, proxyConfig, proxyLogFilePath, logger); + // We skip sending the error message and stack trace here to avoid the possibility + // of leaking any sensitive information into the telemetry. + const errorStatusReportBase = await createStatusReportBase( + ActionName.StartProxy, + getActionsStatus(error), + startedAt, + undefined, + await util.checkDiskUsage(logger), + logger, + ); + if (errorStatusReportBase !== undefined) { + await sendStatusReport(errorStatusReportBase); + } + } } async function startProxy( @@ -133,57 +196,53 @@ async function startProxy( ) { const host = "127.0.0.1"; let port = 49152; - try { - let subprocess: ChildProcess | undefined = undefined; - let tries = 5; - let subprocessError: Error | undefined = undefined; - while (tries-- > 0 && !subprocess && !subprocessError) { - subprocess = spawn( - binPath, - ["-addr", `${host}:${port}`, "-config", "-", "-logfile", logFilePath], - { - detached: true, - stdio: ["pipe", "ignore", "ignore"], - }, - ); - subprocess.unref(); - if (subprocess.pid) { - core.saveState("proxy-process-pid", `${subprocess.pid}`); - } - subprocess.on("error", (error) => { - subprocessError = error; - }); - subprocess.on("exit", (code) => { - if (code !== 0) { - // If the proxy failed to start, try a different port from the ephemeral range [49152, 65535] - port = Math.floor(Math.random() * (65535 - 49152) + 49152); - subprocess = undefined; - } - }); - subprocess.stdin?.write(JSON.stringify(config)); - subprocess.stdin?.end(); - // Wait a little to allow the proxy to start - await util.delay(1000); - } - if (subprocessError) { - // eslint-disable-next-line @typescript-eslint/only-throw-error - throw subprocessError; + let subprocess: ChildProcess | undefined = undefined; + let tries = 5; + let subprocessError: Error | undefined = undefined; + while (tries-- > 0 && !subprocess && !subprocessError) { + subprocess = spawn( + binPath, + ["-addr", `${host}:${port}`, "-config", "-", "-logfile", logFilePath], + { + detached: true, + stdio: ["pipe", "ignore", "ignore"], + }, + ); + subprocess.unref(); + if (subprocess.pid) { + core.saveState("proxy-process-pid", `${subprocess.pid}`); } - logger.info(`Proxy started on ${host}:${port}`); - core.setOutput("proxy_host", host); - core.setOutput("proxy_port", port.toString()); - core.setOutput("proxy_ca_certificate", config.ca.cert); - - const registry_urls = config.all_credentials - .filter((credential) => credential.url !== undefined) - .map((credential) => ({ - type: credential.type, - url: credential.url, - })); - core.setOutput("proxy_urls", JSON.stringify(registry_urls)); - } catch (error) { - core.setFailed(`start-proxy action failed: ${util.getErrorMessage(error)}`); + subprocess.on("error", (error) => { + subprocessError = error; + }); + subprocess.on("exit", (code) => { + if (code !== 0) { + // If the proxy failed to start, try a different port from the ephemeral range [49152, 65535] + port = Math.floor(Math.random() * (65535 - 49152) + 49152); + subprocess = undefined; + } + }); + subprocess.stdin?.write(JSON.stringify(config)); + subprocess.stdin?.end(); + // Wait a little to allow the proxy to start + await util.delay(1000); } + if (subprocessError) { + // eslint-disable-next-line @typescript-eslint/only-throw-error + throw subprocessError; + } + logger.info(`Proxy started on ${host}:${port}`); + core.setOutput("proxy_host", host); + core.setOutput("proxy_port", port.toString()); + core.setOutput("proxy_ca_certificate", config.ca.cert); + + const registry_urls = config.all_credentials + .filter((credential) => credential.url !== undefined) + .map((credential) => ({ + type: credential.type, + url: credential.url, + })); + core.setOutput("proxy_urls", JSON.stringify(registry_urls)); } async function getProxyBinaryPath(logger: Logger): Promise { diff --git a/src/status-report.test.ts b/src/status-report.test.ts index 0d3292637c..b535ef2126 100644 --- a/src/status-report.test.ts +++ b/src/status-report.test.ts @@ -286,6 +286,7 @@ const testCreateInitWithConfigStatusReport = test.macro({ undefined, 1024, undefined, + undefined, ); if (t.truthy(initWithConfigStatusReport)) { diff --git a/src/status-report.ts b/src/status-report.ts index 75f4002214..b0e39aa54b 100644 --- a/src/status-report.ts +++ b/src/status-report.ts @@ -13,6 +13,7 @@ import { } from "./actions-util"; import { getAnalysisKey, getApiClient } from "./api-client"; import { parseRegistriesWithoutCredentials, type Config } from "./config-utils"; +import { DependencyCacheRestoreStatusReport } from "./dependency-caching"; import { DocUrl } from "./doc-url"; import { EnvVar } from "./environment"; import { getRef } from "./git-utils"; @@ -35,11 +36,12 @@ import { } from "./util"; export enum ActionName { - Autobuild = "autobuild", Analyze = "finish", + Autobuild = "autobuild", Init = "init", InitPost = "init-post", ResolveEnvironment = "resolve-environment", + StartProxy = "start-proxy", UploadSarif = "upload-sarif", } @@ -497,6 +499,8 @@ export interface InitWithConfigStatusReport extends InitStatusReport { overlay_base_database_download_size_bytes?: number; /** Time taken to download the overlay-base database, in milliseconds. */ overlay_base_database_download_duration_ms?: number; + /** Stringified JSON object representing information about the results of restoring dependency caches. */ + dependency_caching_restore_results?: DependencyCacheRestoreStatusReport; /** Stringified JSON array of registry configuration objects, from the 'registries' config field or workflow input. **/ registries: string; @@ -522,6 +526,7 @@ export async function createInitWithConfigStatusReport( configFile: string | undefined, totalCacheSize: number, overlayBaseDatabaseStats: OverlayBaseDatabaseDownloadStats | undefined, + dependencyCachingResults: DependencyCacheRestoreStatusReport | undefined, ): Promise { const languages = config.languages.join(","); const paths = (config.originalUserInput.paths || []).join(","); @@ -570,6 +575,7 @@ export async function createInitWithConfigStatusReport( overlayBaseDatabaseStats?.databaseSizeBytes, overlay_base_database_download_duration_ms: overlayBaseDatabaseStats?.databaseDownloadDurationMs, + dependency_caching_restore_results: dependencyCachingResults, query_filters: JSON.stringify( config.originalUserInput["query-filters"] ?? [], ), diff --git a/src/upload-lib.test.ts b/src/upload-lib.test.ts index bfa5e9844c..a1fdf218e1 100644 --- a/src/upload-lib.test.ts +++ b/src/upload-lib.test.ts @@ -3,7 +3,7 @@ import * as path from "path"; import test from "ava"; -import { CodeQuality, CodeScanning } from "./analyses"; +import { AnalysisKind, CodeQuality, CodeScanning } from "./analyses"; import { getRunnerLogger, Logger } from "./logging"; import { setupTests } from "./testing-utils"; import * as uploadLib from "./upload-lib"; @@ -127,27 +127,97 @@ test("finding SARIF files", async (t) => { fs.writeFileSync(path.join(tmpDir, "a.quality.sarif"), ""); fs.writeFileSync(path.join(tmpDir, "dir1", "b.quality.sarif"), ""); + const expectedSarifFiles = [ + path.join(tmpDir, "a.sarif"), + path.join(tmpDir, "b.sarif"), + path.join(tmpDir, "dir1", "d.sarif"), + path.join(tmpDir, "dir1", "dir2", "e.sarif"), + ]; const sarifFiles = uploadLib.findSarifFilesInDir( tmpDir, CodeScanning.sarifPredicate, ); - t.deepEqual(sarifFiles, [ - path.join(tmpDir, "a.sarif"), - path.join(tmpDir, "b.sarif"), - path.join(tmpDir, "dir1", "d.sarif"), - path.join(tmpDir, "dir1", "dir2", "e.sarif"), - ]); + t.deepEqual(sarifFiles, expectedSarifFiles); + const expectedQualitySarifFiles = [ + path.join(tmpDir, "a.quality.sarif"), + path.join(tmpDir, "dir1", "b.quality.sarif"), + ]; const qualitySarifFiles = uploadLib.findSarifFilesInDir( tmpDir, CodeQuality.sarifPredicate, ); - t.deepEqual(qualitySarifFiles, [ - path.join(tmpDir, "a.quality.sarif"), - path.join(tmpDir, "dir1", "b.quality.sarif"), - ]); + t.deepEqual(qualitySarifFiles, expectedQualitySarifFiles); + + const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( + getRunnerLogger(true), + tmpDir, + ); + + t.not(groupedSarifFiles, undefined); + t.not(groupedSarifFiles[AnalysisKind.CodeScanning], undefined); + t.not(groupedSarifFiles[AnalysisKind.CodeQuality], undefined); + t.deepEqual( + groupedSarifFiles[AnalysisKind.CodeScanning], + expectedSarifFiles, + ); + t.deepEqual( + groupedSarifFiles[AnalysisKind.CodeQuality], + expectedQualitySarifFiles, + ); + }); +}); + +test("getGroupedSarifFilePaths - Code Quality file", async (t) => { + await withTmpDir(async (tmpDir) => { + const sarifPath = path.join(tmpDir, "a.quality.sarif"); + fs.writeFileSync(sarifPath, ""); + + const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( + getRunnerLogger(true), + sarifPath, + ); + + t.not(groupedSarifFiles, undefined); + t.is(groupedSarifFiles[AnalysisKind.CodeScanning], undefined); + t.not(groupedSarifFiles[AnalysisKind.CodeQuality], undefined); + t.deepEqual(groupedSarifFiles[AnalysisKind.CodeQuality], [sarifPath]); + }); +}); + +test("getGroupedSarifFilePaths - Code Scanning file", async (t) => { + await withTmpDir(async (tmpDir) => { + const sarifPath = path.join(tmpDir, "a.sarif"); + fs.writeFileSync(sarifPath, ""); + + const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( + getRunnerLogger(true), + sarifPath, + ); + + t.not(groupedSarifFiles, undefined); + t.not(groupedSarifFiles[AnalysisKind.CodeScanning], undefined); + t.is(groupedSarifFiles[AnalysisKind.CodeQuality], undefined); + t.deepEqual(groupedSarifFiles[AnalysisKind.CodeScanning], [sarifPath]); + }); +}); + +test("getGroupedSarifFilePaths - Other file", async (t) => { + await withTmpDir(async (tmpDir) => { + const sarifPath = path.join(tmpDir, "a.json"); + fs.writeFileSync(sarifPath, ""); + + const groupedSarifFiles = await uploadLib.getGroupedSarifFilePaths( + getRunnerLogger(true), + sarifPath, + ); + + t.not(groupedSarifFiles, undefined); + t.not(groupedSarifFiles[AnalysisKind.CodeScanning], undefined); + t.is(groupedSarifFiles[AnalysisKind.CodeQuality], undefined); + t.deepEqual(groupedSarifFiles[AnalysisKind.CodeScanning], [sarifPath]); }); }); diff --git a/src/upload-lib.ts b/src/upload-lib.ts index 650e7a803a..cfa362b678 100644 --- a/src/upload-lib.ts +++ b/src/upload-lib.ts @@ -459,6 +459,79 @@ export function getSarifFilePaths( return sarifFiles; } +type GroupedSarifFiles = Partial>; + +/** + * Finds SARIF files in `sarifPath`, and groups them by analysis kind, following `SarifScanOrder`. + * + * @param logger The logger to use. + * @param sarifPath The path of a file or directory to recursively scan for SARIF files. + * @returns The `.sarif` files found in `sarifPath`, grouped by analysis kind. + */ +export async function getGroupedSarifFilePaths( + logger: Logger, + sarifPath: string, +): Promise { + const stats = fs.statSync(sarifPath, { throwIfNoEntry: false }); + + if (stats === undefined) { + // This is always a configuration error, even for first-party runs. + throw new ConfigurationError(`Path does not exist: ${sarifPath}`); + } + + const results: GroupedSarifFiles = {}; + + if (stats.isDirectory()) { + let unassignedSarifFiles = findSarifFilesInDir( + sarifPath, + (name) => path.extname(name) === ".sarif", + ); + logger.debug( + `Found the following .sarif files in ${sarifPath}: ${unassignedSarifFiles.join(", ")}`, + ); + + for (const analysisConfig of analyses.SarifScanOrder) { + const filesForCurrentAnalysis = unassignedSarifFiles.filter( + analysisConfig.sarifPredicate, + ); + if (filesForCurrentAnalysis.length > 0) { + logger.debug( + `The following SARIF files are for ${analysisConfig.name}: ${filesForCurrentAnalysis.join(", ")}`, + ); + // Looping through the array a second time is not efficient, but more readable. + // Change this to one loop for both calls to `filter` if this becomes a bottleneck. + unassignedSarifFiles = unassignedSarifFiles.filter( + (name) => !analysisConfig.sarifPredicate(name), + ); + results[analysisConfig.kind] = filesForCurrentAnalysis; + } else { + logger.debug(`Found no SARIF files for ${analysisConfig.name}`); + } + } + + if (unassignedSarifFiles.length !== 0) { + logger.warning( + `Found files in ${sarifPath} which do not belong to any analysis: ${unassignedSarifFiles.join(", ")}`, + ); + } + } else { + for (const analysisConfig of analyses.SarifScanOrder) { + if ( + analysisConfig.kind === analyses.AnalysisKind.CodeScanning || + analysisConfig.sarifPredicate(sarifPath) + ) { + logger.debug( + `Using '${sarifPath}' as a SARIF file for ${analysisConfig.name}.`, + ); + results[analysisConfig.kind] = [sarifPath]; + break; + } + } + } + + return results; +} + // Counts the number of results in the given SARIF file function countResultsInSarif(sarif: string): number { let numResults = 0; @@ -655,6 +728,7 @@ export async function uploadSpecifiedFiles( const gitHubVersion = await getGitHubVersion(); let sarif: SarifFile; + category = uploadTarget.fixCategory(logger, category); if (sarifPaths.length > 1) { // Validate that the files we were asked to upload are all valid SARIF files diff --git a/src/upload-sarif-action.ts b/src/upload-sarif-action.ts index 4da0427490..b9eced9d39 100644 --- a/src/upload-sarif-action.ts +++ b/src/upload-sarif-action.ts @@ -1,5 +1,3 @@ -import * as fs from "fs"; - import * as core from "@actions/core"; import * as actionsUtil from "./actions-util"; @@ -18,6 +16,7 @@ import { isThirdPartyAnalysis, } from "./status-report"; import * as upload_lib from "./upload-lib"; +import { uploadSarif } from "./upload-sarif"; import { ConfigurationError, checkActionVersion, @@ -32,60 +31,6 @@ interface UploadSarifStatusReport extends StatusReportBase, upload_lib.UploadStatusReport {} -/** - * Searches for SARIF files for the given `analysis` in the given `sarifPath`. - * If any are found, then they are uploaded to the appropriate endpoint for the given `analysis`. - * - * @param logger The logger to use. - * @param features Information about FFs. - * @param sarifPath The path to a SARIF file or directory containing SARIF files. - * @param pathStats Information about `sarifPath`. - * @param checkoutPath The checkout path. - * @param analysis The configuration of the analysis we should upload SARIF files for. - * @param category The SARIF category to use for the upload. - * @returns The result of uploading the SARIF file(s) or `undefined` if there are none. - */ -async function findAndUpload( - logger: Logger, - features: Features, - sarifPath: string, - pathStats: fs.Stats, - checkoutPath: string, - analysis: analyses.AnalysisConfig, - category?: string, -): Promise { - let sarifFiles: string[] | undefined; - - if (pathStats.isDirectory()) { - sarifFiles = upload_lib.findSarifFilesInDir( - sarifPath, - analysis.sarifPredicate, - ); - } else if ( - pathStats.isFile() && - (analysis.sarifPredicate(sarifPath) || - (analysis.kind === analyses.AnalysisKind.CodeScanning && - !analyses.CodeQuality.sarifPredicate(sarifPath))) - ) { - sarifFiles = [sarifPath]; - } else { - return undefined; - } - - if (sarifFiles.length !== 0) { - return await upload_lib.uploadSpecifiedFiles( - sarifFiles, - checkoutPath, - category, - features, - logger, - analysis, - ); - } - - return undefined; -} - async function sendSuccessStatusReport( startedAt: Date, uploadStats: upload_lib.UploadStatusReport, @@ -144,56 +89,37 @@ async function run() { const sarifPath = actionsUtil.getRequiredInput("sarif_file"); const checkoutPath = actionsUtil.getRequiredInput("checkout_path"); const category = actionsUtil.getOptionalInput("category"); - const pathStats = fs.lstatSync(sarifPath, { throwIfNoEntry: false }); - - if (pathStats === undefined) { - throw new ConfigurationError(`Path does not exist: ${sarifPath}.`); - } - const sarifIds: Array<{ analysis: string; id: string }> = []; - const uploadResult = await findAndUpload( + const uploadResults = await uploadSarif( logger, features, - sarifPath, - pathStats, checkoutPath, - analyses.CodeScanning, + sarifPath, category, ); - if (uploadResult !== undefined) { - core.setOutput("sarif-id", uploadResult.sarifID); - sarifIds.push({ - analysis: analyses.AnalysisKind.CodeScanning, - id: uploadResult.sarifID, - }); + + // Fail if we didn't upload anything. + if (Object.keys(uploadResults).length === 0) { + throw new ConfigurationError( + `No SARIF files found to upload in "${sarifPath}".`, + ); } - // If there are `.quality.sarif` files in `sarifPath`, then upload those to the code quality service. - const qualityUploadResult = await findAndUpload( - logger, - features, - sarifPath, - pathStats, - checkoutPath, - analyses.CodeQuality, - actionsUtil.fixCodeQualityCategory(logger, category), - ); - if (qualityUploadResult !== undefined) { - sarifIds.push({ - analysis: analyses.AnalysisKind.CodeQuality, - id: qualityUploadResult.sarifID, - }); + const codeScanningResult = + uploadResults[analyses.AnalysisKind.CodeScanning]; + if (codeScanningResult !== undefined) { + core.setOutput("sarif-id", codeScanningResult.sarifID); } - core.setOutput("sarif-ids", JSON.stringify(sarifIds)); + core.setOutput("sarif-ids", JSON.stringify(uploadResults)); // We don't upload results in test mode, so don't wait for processing if (isInTestMode()) { core.debug("In test mode. Waiting for processing is disabled."); } else if (actionsUtil.getRequiredInput("wait-for-processing") === "true") { - if (uploadResult !== undefined) { + if (codeScanningResult !== undefined) { await upload_lib.waitForProcessing( getRepositoryNwo(), - uploadResult.sarifID, + codeScanningResult.sarifID, logger, ); } @@ -202,7 +128,7 @@ async function run() { } await sendSuccessStatusReport( startedAt, - uploadResult?.statusReport || {}, + codeScanningResult?.statusReport || {}, logger, ); } catch (unwrappedError) { diff --git a/src/upload-sarif.test.ts b/src/upload-sarif.test.ts new file mode 100644 index 0000000000..893330eda6 --- /dev/null +++ b/src/upload-sarif.test.ts @@ -0,0 +1,185 @@ +import * as fs from "fs"; +import * as path from "path"; + +import test, { ExecutionContext } from "ava"; +import * as sinon from "sinon"; + +import { AnalysisKind, getAnalysisConfig } from "./analyses"; +import { getRunnerLogger } from "./logging"; +import { createFeatures, setupTests } from "./testing-utils"; +import { UploadResult } from "./upload-lib"; +import * as uploadLib from "./upload-lib"; +import { uploadSarif } from "./upload-sarif"; +import * as util from "./util"; + +setupTests(test); + +interface UploadSarifExpectedResult { + uploadResult?: UploadResult; + expectedFiles?: string[]; +} + +const uploadSarifMacro = test.macro({ + exec: async ( + t: ExecutionContext, + sarifFiles: string[], + sarifPath: (tempDir: string) => string = (tempDir) => tempDir, + expectedResult: Partial>, + ) => { + await util.withTmpDir(async (tempDir) => { + const logger = getRunnerLogger(true); + const testPath = sarifPath(tempDir); + const features = createFeatures([]); + + const toFullPath = (filename: string) => path.join(tempDir, filename); + + const uploadSpecifiedFiles = sinon.stub( + uploadLib, + "uploadSpecifiedFiles", + ); + + for (const analysisKind of Object.values(AnalysisKind)) { + uploadSpecifiedFiles + .withArgs( + sinon.match.any, + sinon.match.any, + sinon.match.any, + features, + logger, + getAnalysisConfig(analysisKind), + ) + .resolves(expectedResult[analysisKind as AnalysisKind]?.uploadResult); + } + + const fullSarifPaths = sarifFiles.map(toFullPath); + for (const sarifFile of fullSarifPaths) { + fs.writeFileSync(sarifFile, ""); + } + + const actual = await uploadSarif(logger, features, "", testPath); + + for (const analysisKind of Object.values(AnalysisKind)) { + const analysisKindResult = expectedResult[analysisKind]; + if (analysisKindResult) { + // We are expecting a result for this analysis kind, check that we have it. + t.deepEqual(actual[analysisKind], analysisKindResult.uploadResult); + // Additionally, check that the mocked `uploadSpecifiedFiles` was called with only the file paths + // that we expected it to be called with. + t.assert( + uploadSpecifiedFiles.calledWith( + analysisKindResult.expectedFiles?.map(toFullPath) ?? + fullSarifPaths, + sinon.match.any, + sinon.match.any, + features, + logger, + getAnalysisConfig(analysisKind), + ), + ); + } else { + // Otherwise, we are not expecting a result for this analysis kind. However, note that `undefined` + // is also returned by our mocked `uploadSpecifiedFiles` when there is no expected result for this + // analysis kind. + t.is(actual[analysisKind], undefined); + // Therefore, we also check that the mocked `uploadSpecifiedFiles` was not called for this analysis kind. + t.assert( + !uploadSpecifiedFiles.calledWith( + sinon.match.any, + sinon.match.any, + sinon.match.any, + features, + logger, + getAnalysisConfig(analysisKind), + ), + `uploadSpecifiedFiles was called for ${analysisKind}, but should not have been.`, + ); + } + } + }); + }, + title: (providedTitle = "") => `uploadSarif - ${providedTitle}`, +}); + +test( + "SARIF file", + uploadSarifMacro, + ["test.sarif"], + (tempDir) => path.join(tempDir, "test.sarif"), + { + "code-scanning": { + uploadResult: { + statusReport: {}, + sarifID: "code-scanning-sarif", + }, + }, + }, +); + +test( + "JSON file", + uploadSarifMacro, + ["test.json"], + (tempDir) => path.join(tempDir, "test.json"), + { + "code-scanning": { + uploadResult: { + statusReport: {}, + sarifID: "code-scanning-sarif", + }, + }, + }, +); + +test( + "Code Scanning files", + uploadSarifMacro, + ["test.json", "test.sarif"], + undefined, + { + "code-scanning": { + uploadResult: { + statusReport: {}, + sarifID: "code-scanning-sarif", + }, + expectedFiles: ["test.sarif"], + }, + }, +); + +test( + "Code Quality file", + uploadSarifMacro, + ["test.quality.sarif"], + (tempDir) => path.join(tempDir, "test.quality.sarif"), + { + "code-quality": { + uploadResult: { + statusReport: {}, + sarifID: "code-quality-sarif", + }, + }, + }, +); + +test( + "Mixed files", + uploadSarifMacro, + ["test.sarif", "test.quality.sarif"], + undefined, + { + "code-scanning": { + uploadResult: { + statusReport: {}, + sarifID: "code-scanning-sarif", + }, + expectedFiles: ["test.sarif"], + }, + "code-quality": { + uploadResult: { + statusReport: {}, + sarifID: "code-quality-sarif", + }, + expectedFiles: ["test.quality.sarif"], + }, + }, +); diff --git a/src/upload-sarif.ts b/src/upload-sarif.ts new file mode 100644 index 0000000000..34b912489d --- /dev/null +++ b/src/upload-sarif.ts @@ -0,0 +1,51 @@ +import * as analyses from "./analyses"; +import { FeatureEnablement } from "./feature-flags"; +import { Logger } from "./logging"; +import * as upload_lib from "./upload-lib"; +import { unsafeEntriesInvariant } from "./util"; + +// Maps analysis kinds to SARIF IDs. +export type UploadSarifResults = Partial< + Record +>; + +/** + * Finds SARIF files in `sarifPath` and uploads them to the appropriate services. + * + * @param logger The logger to use. + * @param features Information about enabled features. + * @param checkoutPath The path where the repository was checked out at. + * @param sarifPath The path to the file or directory to upload. + * @param category The analysis category. + * + * @returns A partial mapping from analysis kinds to the upload results. + */ +export async function uploadSarif( + logger: Logger, + features: FeatureEnablement, + checkoutPath: string, + sarifPath: string, + category?: string, +): Promise { + const sarifGroups = await upload_lib.getGroupedSarifFilePaths( + logger, + sarifPath, + ); + + const uploadResults: UploadSarifResults = {}; + for (const [analysisKind, sarifFiles] of unsafeEntriesInvariant( + sarifGroups, + )) { + const analysisConfig = analyses.getAnalysisConfig(analysisKind); + uploadResults[analysisKind] = await upload_lib.uploadSpecifiedFiles( + sarifFiles, + checkoutPath, + category, + features, + logger, + analysisConfig, + ); + } + + return uploadResults; +} diff --git a/src/util.ts b/src/util.ts index db7ba6cfda..e7c29ed12e 100644 --- a/src/util.ts +++ b/src/util.ts @@ -1287,3 +1287,27 @@ export async function asyncSome( export function isDefined(value: T | null | undefined): value is T { return value !== undefined && value !== null; } + +/** Like `Object.keys`, but typed so that the elements of the resulting array have the + * same type as the keys of the input object. Note that this may not be sound if the input + * object has been cast to `T` from a subtype of `T` and contains additional keys that + * are not represented by `keyof T`. + */ +export function unsafeKeysInvariant>( + object: T, +): Array { + return Object.keys(object) as Array; +} + +/** Like `Object.entries`, but typed so that the key elements of the result have the + * same type as the keys of the input object. Note that this may not be sound if the input + * object has been cast to `T` from a subtype of `T` and contains additional keys that + * are not represented by `keyof T`. + */ +export function unsafeEntriesInvariant>( + object: T, +): Array<[keyof T, Exclude]> { + return Object.entries(object).filter( + ([_, val]) => val !== undefined, + ) as Array<[keyof T, Exclude]>; +}