diff --git a/.eslintignore b/.eslintignore index 42ceb9a..e69de29 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,4 +0,0 @@ -dist/ -lib/ -node_modules/ -jest.config.js diff --git a/.eslintrc.json b/.eslintrc.json index bca4a7a..e69de29 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,90 +0,0 @@ -{ - "plugins": ["jest", "@typescript-eslint", "prettier", "unicorn"], - "extends": ["plugin:unicorn/recommended", "plugin:github/recommended", "plugin:prettier/recommended"], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 2020, - "sourceType": "module", - "extraFileExtensions": [".mjs"], - "ecmaFeatures": { - "impliedStrict": true - }, - "project": "./tsconfig.json" - }, - "env": { - "node": true, - "es6": true, - "jest/globals": true, - "es2020": true - }, - "rules": { - // Error out for code formatting errors - "prettier/prettier": "error", - // Namespaces or sometimes needed - "import/no-namespace": "off", - // Properly format comments - "spaced-comment": ["error", "always"], - "lines-around-comment": [ - "error", - { - "beforeBlockComment": true, - "beforeLineComment": true, - "allowBlockStart": true, - "allowObjectStart": true, - "allowArrayStart": true, - "allowClassStart": true, - "ignorePattern": "pragma|ts-ignore" - } - ], - // Mandatory spacing - "padding-line-between-statements": [ - "error", - { - "blankLine": "always", - "prev": "*", - "next": "return" - }, - { - "blankLine": "always", - "prev": "directive", - "next": "*" - }, - { - "blankLine": "any", - "prev": "directive", - "next": "directive" - } - ], - // Enforce camelCase - "camelcase": "error", - // Allow forOfStatements - "no-restricted-syntax": ["error", "ForInStatement", "LabeledStatement", "WithStatement"], - // Continue is viable in forOf loops in generators - "no-continue": "off", - // From experience, named exports are almost always desired. I got tired of this rule - "import/prefer-default-export": "off", - // Unused vars are useful to keep method signatures consistent and documented - "@typescript-eslint/no-unused-vars": "off", - // For this project only use kebab-case - "unicorn/filename-case": [ - "error", - { - "cases": { - "kebabCase": true - } - } - ], - // Allow Array.from(set) mitigate TS2569 which would require '--downlevelIteration' - "unicorn/prefer-spread": "off", - // Temp disable to prevent mixing changes with other PRs - "i18n-text/no-en": "off" - }, - "overrides": [ - { - "files": ["jest.setup.js"], - "rules": { - "import/no-commonjs": "off" - } - } - ] -} diff --git a/.github/workflows/integrity-check.yml b/.github/workflows/integrity-check.yml index 3cbf618..6ed6185 100644 --- a/.github/workflows/integrity-check.yml +++ b/.github/workflows/integrity-check.yml @@ -2,13 +2,17 @@ name: Integrity on: push: { branches: [main] } - pull_request: {} + pull_request: + types: [opened, synchronize, reopened, labeled] permissions: contents: read checks: write statuses: write +env: + CODECOV_TOKEN: '2f2eb890-30e2-4724-83eb-7633832cf0de' + concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true @@ -18,17 +22,34 @@ jobs: name: Tests runs-on: ubuntu-latest steps: - - name: Harden the runner (Audit all outbound calls) - uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1 - with: - egress-policy: audit - - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + - uses: actions/checkout@v7 + - name: Install package manager (from package.json) + run: | + corepack enable + corepack install + - uses: actions/setup-node@v6 with: node-version: '24' - - run: yarn + - name: Resolve yarn cache folder + id: yarn-config + run: echo "cacheFolder=$(yarn config get cacheFolder)" >> "$GITHUB_OUTPUT" + - name: Restore yarn install cache (node_modules + cacheFolder + install-state) + uses: actions/cache@v4 + with: + path: | + ${{ steps.yarn-config.outputs.cacheFolder }} + .yarn/install-state.gz + key: yarn-v2-${{ runner.os }}-node-18-${{ hashFiles('yarn.lock') }} + restore-keys: | + yarn-v2-${{ runner.os }}-node-18- + - name: Install deps + env: + YARN_ENABLE_HARDENED_MODE: 'false' + run: | + case "$(yarn --version)" in 1.*) echo 'expected up-to-date yarn version'; exit 1 ;; esac + yarn install --immutable - run: yarn lint - - run: yarn test:ci + - run: yarn test:ci --coverage + - run: bash <(curl -s https://codecov.io/bash) - run: yarn build || { echo "build command should always succeed" ; exit 61; } # - run: yarn build --quiet && git diff --quiet dist || { echo "dist should be auto generated" ; git diff dist ; exit 62; } diff --git a/.github/workflows/validate-community-plugins.yml b/.github/workflows/validate-community-plugins.yml new file mode 100644 index 0000000..762a37d --- /dev/null +++ b/.github/workflows/validate-community-plugins.yml @@ -0,0 +1,202 @@ +name: Validate Community Plugins + +on: + workflow_dispatch: + inputs: + plugin_filter: + description: 'Filter plugins by name (regex pattern, empty = all)' + required: false + default: '' + unity_version: + description: 'Override Unity version (empty = use plugin default)' + required: false + default: '' + +permissions: + contents: read + issues: write + +jobs: + load-plugins: + name: Load Plugin Registry + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.parse.outputs.matrix }} + plugin_count: ${{ steps.parse.outputs.count }} + steps: + - uses: actions/checkout@v4 + + - name: Parse plugin registry + id: parse + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const yaml = require('js-yaml'); + + const registry = yaml.load(fs.readFileSync('community-plugins.yml', 'utf8')); + let plugins = registry.plugins || []; + + // Apply name filter if provided + const filter = '${{ github.event.inputs.plugin_filter }}'; + if (filter) { + const regex = new RegExp(filter, 'i'); + plugins = plugins.filter(p => regex.test(p.name)); + } + + // Expand platform matrix + const matrix = []; + for (const plugin of plugins) { + const platforms = plugin.platforms || ['StandaloneLinux64']; + for (const platform of platforms) { + matrix.push({ + name: plugin.name, + package: plugin.package, + source: plugin.source || 'git', + unity: '${{ github.event.inputs.unity_version }}' || plugin.unity || '2021.3', + platform: platform, + timeout: plugin.timeout || 30 + }); + } + } + + core.setOutput('matrix', JSON.stringify({ include: matrix })); + core.setOutput('count', matrix.length); + console.log(`Found ${matrix.length} plugin-platform combinations to validate`); + + validate: + name: '${{ matrix.name }} (${{ matrix.platform }})' + needs: load-plugins + if: needs.load-plugins.outputs.plugin_count > 0 + runs-on: ubuntu-latest + timeout-minutes: ${{ fromJson(matrix.timeout) }} + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.load-plugins.outputs.matrix) }} + steps: + - uses: actions/checkout@v4 + + - name: Create test project + run: | + mkdir -p test-project/Assets + mkdir -p test-project/Packages + mkdir -p test-project/ProjectSettings + + # Create minimal manifest.json + if [ "${{ matrix.source }}" = "git" ]; then + cat > test-project/Packages/manifest.json << 'MANIFEST' + { + "dependencies": { + "com.unity.modules.imgui": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0" + } + } + MANIFEST + + # Add git package via manifest + cd test-project + python3 -c " + import sys, json + manifest = json.load(sys.stdin) + manifest['dependencies']['${{ matrix.name }}'] = '${{ matrix.package }}' + json.dump(manifest, sys.stdout, indent=2) + " < Packages/manifest.json > Packages/manifest.tmp && mv Packages/manifest.tmp Packages/manifest.json + cd .. + fi + + # Create minimal ProjectSettings + cat > test-project/ProjectSettings/ProjectVersion.txt << EOF + m_EditorVersion: ${{ matrix.unity }} + EOF + + - name: Build with unity-builder + uses: ./ + id: build + with: + projectPath: test-project + targetPlatform: ${{ matrix.platform }} + unityVersion: ${{ matrix.unity }} + continue-on-error: true + + - name: Record result + if: always() + run: | + STATUS="${{ steps.build.outcome }}" + { + echo "## ${{ matrix.name }} — ${{ matrix.platform }}" + echo "" + if [ "$STATUS" = "success" ]; then + echo "✅ **PASSED** — Compiled and built successfully" + else + echo "❌ **FAILED** — Build or compilation failed" + fi + echo "" + echo "- Unity: ${{ matrix.unity }}" + echo "- Platform: ${{ matrix.platform }}" + echo "- Source: ${{ matrix.source }}" + echo "- Package: \`${{ matrix.package }}\`" + } >> "$GITHUB_STEP_SUMMARY" + + report: + name: Validation Report + needs: [load-plugins, validate] + if: always() + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Generate summary + uses: actions/github-script@v7 + with: + script: | + const { data: run } = await github.rest.actions.listJobsForWorkflowRun({ + owner: context.repo.owner, + repo: context.repo.repo, + run_id: context.runId + }); + + const validateJobs = run.jobs.filter(j => j.name.startsWith('validate')); + const passed = validateJobs.filter(j => j.conclusion === 'success').length; + const failed = validateJobs.filter(j => j.conclusion === 'failure').length; + const total = validateJobs.length; + + let summary = `# Community Plugin Validation Report\n\n`; + summary += `**${passed}/${total} passed** | ${failed} failed\n\n`; + summary += `| Plugin | Platform | Status |\n|--------|----------|--------|\n`; + + for (const job of validateJobs) { + const icon = job.conclusion === 'success' ? '✅' : '❌'; + summary += `| ${job.name} | | ${icon} ${job.conclusion} |\n`; + } + + await core.summary.addRaw(summary).write(); + + // Create or update issue if there are failures + if (failed > 0) { + const title = `Community Plugin Validation: ${failed} failure(s) — ${new Date().toISOString().split('T')[0]}`; + const body = summary + `\n\n[Workflow Run](${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId})`; + + const { data: issues } = await github.rest.issues.listForRepo({ + owner: context.repo.owner, + repo: context.repo.repo, + state: 'open', + labels: 'community-plugin-validation' + }); + + if (issues.length > 0) { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issues[0].number, + body: body + }); + } else { + await github.rest.issues.create({ + owner: context.repo.owner, + repo: context.repo.repo, + title: title, + body: body, + labels: ['community-plugin-validation'] + }); + } + } diff --git a/.github/workflows/validate-orchestrator.yml b/.github/workflows/validate-orchestrator.yml new file mode 100644 index 0000000..137ab8f --- /dev/null +++ b/.github/workflows/validate-orchestrator.yml @@ -0,0 +1,255 @@ +name: Validate Orchestrator Compatibility + +# ============================================================================== +# Essential plugin health checks — runs on every PR and push. +# Fast (~5 min): compilation, unit tests, plugin interface, type declarations. +# +# For exhaustive integration tests (k8s, AWS, local-docker, rclone) see +# validate-orchestrator-integration.yml which runs on a daily cron. +# ============================================================================== + +on: + workflow_dispatch: + push: + branches: [main] + paths: + - 'src/model/orchestrator-plugin.ts' + - 'src/model/build-parameters.ts' + - 'src/model/input.ts' + - 'src/model/github.ts' + - 'src/model/cli/cli.ts' + - 'src/model/input-readers/**' + - 'src/index.ts' + - 'src/types/game-ci-orchestrator.d.ts' + - 'action.yml' + - 'package.json' + - 'yarn.lock' + - '.github/workflows/validate-orchestrator.yml' + pull_request: + branches: [main] + paths: + - 'src/model/orchestrator-plugin.ts' + - 'src/model/build-parameters.ts' + - 'src/model/input.ts' + - 'src/model/github.ts' + - 'src/model/cli/cli.ts' + - 'src/model/input-readers/**' + - 'src/index.ts' + - 'src/types/game-ci-orchestrator.d.ts' + - 'action.yml' + - 'package.json' + - 'yarn.lock' + - '.github/workflows/validate-orchestrator.yml' + +permissions: + contents: read + packages: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + # ============================================================================ + # PLUGIN ARCHITECTURE HEALTH CHECK + # ============================================================================ + # Validates that: + # 1. unity-builder compiles and its unit tests pass + # 2. Plugin loader degrades gracefully without orchestrator + # 3. Orchestrator compiles and its unit tests pass + # 4. Plugin loader loads all services when orchestrator is installed + # 5. Type declarations match actual exports + # ============================================================================ + plugin-health: + name: Plugin Architecture Health + runs-on: ubuntu-latest + steps: + - name: Checkout unity-builder + uses: actions/checkout@v4 + + - name: Checkout orchestrator + uses: actions/checkout@v4 + with: + repository: game-ci/orchestrator + ref: ${{ github.head_ref || github.ref_name }} + path: orchestrator-standalone + continue-on-error: true + id: orchestrator-branch + + - name: Fallback to orchestrator main branch + if: steps.orchestrator-branch.outcome == 'failure' + uses: actions/checkout@v4 + with: + repository: game-ci/orchestrator + path: orchestrator-standalone + + - name: Install package manager (from package.json) + run: | + corepack enable + corepack install + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Resolve yarn cache folder + id: yarn-config + run: echo "cacheFolder=$(yarn config get cacheFolder)" >> "$GITHUB_OUTPUT" + - name: Restore yarn install cache (node_modules + cacheFolder + install-state) + uses: actions/cache@v4 + with: + path: | + ${{ steps.yarn-config.outputs.cacheFolder }} + .yarn/install-state.gz + key: yarn-v2-${{ runner.os }}-node-24-${{ hashFiles('yarn.lock') }} + restore-keys: | + yarn-v2-${{ runner.os }}-node-24- + + # --- unity-builder compilation and tests --- + - name: Install unity-builder dependencies + env: + YARN_ENABLE_HARDENED_MODE: 'false' + run: | + case "$(yarn --version)" in 1.*) echo 'expected up-to-date yarn version'; exit 1 ;; esac + yarn install --immutable + + - name: Build unity-builder + run: | + echo "Building unity-builder TypeScript..." + npx tsc + echo "✓ unity-builder compiles successfully" + + - name: Run orchestrator-plugin unit tests + run: | + echo "Running orchestrator-plugin unit tests..." + yarn vitest run orchestrator-plugin + + # --- Plugin loader without orchestrator --- + - name: Verify plugin loader returns undefined without orchestrator + run: | + echo "Checking plugin loader handles missing @game-ci/orchestrator..." + node -e " + const { loadOrchestratorPlugin } = require('./lib/model/orchestrator-plugin'); + (async () => { + const plugin = await loadOrchestratorPlugin(); + if (plugin !== undefined) { + console.error('ERROR: loadOrchestratorPlugin should return undefined when package not installed'); + process.exit(1); + } + console.log('✓ loadOrchestratorPlugin() returns undefined when package not installed'); + })(); + " + + - name: Verify orchestrator type declarations exist + run: | + if [ -f "src/types/game-ci-orchestrator.d.ts" ]; then + echo "✓ Type declarations for @game-ci/orchestrator exist" + else + echo "::error::Missing type declarations: src/types/game-ci-orchestrator.d.ts" + exit 1 + fi + + # --- Orchestrator compilation and tests --- + - name: Build and pack orchestrator + working-directory: orchestrator-standalone + run: | + yarn install --immutable + echo "Building orchestrator..." + npx tsc + echo "✓ orchestrator compiles successfully" + echo "Packing orchestrator as tarball..." + npm pack + + - name: Run orchestrator unit tests + working-directory: orchestrator-standalone + run: | + echo "Running orchestrator unit tests..." + yarn vitest run 2>&1 | tail -30 + + # --- Plugin loader with orchestrator installed --- + - name: Install orchestrator into unity-builder + run: | + echo "Installing orchestrator into unity-builder workspace..." + npm install ./orchestrator-standalone/game-ci-orchestrator-*.tgz --no-save --legacy-peer-deps + + - name: Verify plugin loader returns exports with orchestrator installed + run: | + echo "Checking plugin loader returns defined exports..." + node -e " + const { loadOrchestratorPlugin } = require('./lib/model/orchestrator-plugin'); + (async () => { + const plugin = await loadOrchestratorPlugin(); + if (plugin === undefined) { + console.error('ERROR: loadOrchestratorPlugin should return defined plugin when package is installed'); + process.exit(1); + } + const lifecycleMethods = [ + 'initialize', 'canHandleBuild', 'handleBuild', + 'beforeLocalBuild', 'afterLocalBuild', 'handlePostBuild', + ]; + for (const method of lifecycleMethods) { + if (typeof plugin[method] !== 'function') { + console.error('ERROR: plugin.' + method + ' should be a function, got ' + typeof plugin[method]); + process.exit(1); + } + } + console.log('✓ loadOrchestratorPlugin() returns plugin with all ' + lifecycleMethods.length + ' lifecycle methods'); + })(); + " + + - name: Verify type declarations match orchestrator exports + run: | + echo "Checking type declarations align with orchestrator exports..." + node -e " + const orch = require('@game-ci/orchestrator'); + const expectedExports = [ + 'Orchestrator', 'BuildReliabilityService', 'TestWorkflowService', + 'HotRunnerService', 'OutputService', 'OutputTypeRegistry', + 'ArtifactUploadHandler', 'IncrementalSyncService', + 'ChildWorkspaceService', 'LocalCacheService', 'SubmoduleProfileService', + 'LfsAgentService', 'GitHooksService', + ]; + const missing = expectedExports.filter(e => orch[e] === undefined); + if (missing.length > 0) { + console.error('ERROR: Missing exports from @game-ci/orchestrator:', missing.join(', ')); + process.exit(1); + } + console.log('✓ All ' + expectedExports.length + ' declared exports present in orchestrator package'); + " + + - name: Smoke test orchestrator build wiring + run: | + echo "Verifying orchestrator build wiring end-to-end..." + node -e " + const { loadOrchestratorPlugin } = require('./lib/model/orchestrator-plugin'); + + (async () => { + // Verify plugin loads successfully with orchestrator installed + const plugin = await loadOrchestratorPlugin(); + if (plugin === undefined) { + console.error('ERROR: plugin should be defined when orchestrator is installed'); + process.exit(1); + } + + // Verify all lifecycle methods are callable + const lifecycleMethods = [ + 'initialize', 'canHandleBuild', 'handleBuild', + 'beforeLocalBuild', 'afterLocalBuild', 'handlePostBuild', + ]; + for (const m of lifecycleMethods) { + if (typeof plugin[m] !== 'function') { + console.error('ERROR: plugin.' + m + ' should be a function, got ' + typeof plugin[m]); + process.exit(1); + } + } + console.log('✓ Plugin has all ' + lifecycleMethods.length + ' lifecycle methods'); + + // Verify canHandleBuild returns a boolean + const canHandle = plugin.canHandleBuild(); + if (typeof canHandle !== 'boolean') { + console.error('ERROR: canHandleBuild() should return a boolean, got ' + typeof canHandle); + process.exit(1); + } + console.log('✓ canHandleBuild() returns boolean'); + + console.log('✓ Plugin architecture wiring verified'); + })(); + " diff --git a/.gitignore b/.gitignore index 90e072c..0ec2fe4 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,6 @@ yarn-error.log .orig $LOG_FILE temp/ -**/.DS_Store \ No newline at end of file +**/.DS_Store +.yarn/cache +.yarn/install-state.gz \ No newline at end of file diff --git a/.oxfmtrc.json b/.oxfmtrc.json new file mode 100644 index 0000000..3bf1670 --- /dev/null +++ b/.oxfmtrc.json @@ -0,0 +1,17 @@ +{ + "semi": true, + "singleQuote": true, + "trailingComma": "all", + "printWidth": 100, + "proseWrap": "preserve", + "sortPackageJson": false, + "ignorePatterns": [ + "**/node_modules/**", + "**/dist/**", + "**/coverage/**", + "**/.yarn/**", + "default-build-script/**", + "test-runner/**", + "platforms/**" + ] +} diff --git a/.oxlintrc.json b/.oxlintrc.json new file mode 100644 index 0000000..0b83443 --- /dev/null +++ b/.oxlintrc.json @@ -0,0 +1,58 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "plugins": ["typescript", "vitest", "unicorn", "oxc"], + "categories": { + "correctness": "error", + "suspicious": "error", + "perf": "error" + }, + "rules": { + "vitest/require-mock-type-parameters": "off", + "vitest/valid-title": "off", + "vitest/valid-describe-callback": "off", + "vitest/expect-expect": "off", + "vitest/no-conditional-tests": "off", + "vitest/no-conditional-expect": "off", + "vitest/require-to-throw-message": "off", + "vitest/no-disabled-tests": "warn", + "unicorn/prefer-array-flat-map": "warn", + "typescript/no-explicit-any": "warn", + "typescript/ban-ts-comment": "off", + "typescript/no-namespace": "off", + "typescript/no-extraneous-class": "off", + "no-bitwise": "off", + "no-shadow": "off", + "no-await-in-loop": "off", + "no-underscore-dangle": "off", + "unicorn/no-array-sort": "off", + "unicorn/prefer-set-has": "off", + "unicorn/consistent-function-scoping": "off", + "unicorn/no-useless-spread": "warn", + "eslint/preserve-caught-error": "warn", + "oxc/no-map-spread": "warn" + }, + "overrides": [ + { + "files": ["**/*.test.ts", "**/*.spec.ts"], + "rules": { + "typescript/no-explicit-any": "off", + "no-unused-vars": "off" + } + } + ], + "env": { + "browser": false, + "node": true, + "es2024": true, + "vitest/globals": true + }, + "ignorePatterns": [ + "**/node_modules/**", + "**/dist/**", + "**/coverage/**", + "**/.yarn/**", + "default-build-script/**", + "test-runner/**", + "platforms/**" + ] +} diff --git a/.prettierignore b/.prettierignore index cb3fd15..e69de29 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,2 +0,0 @@ -**/node_modules/** -**/dist/** diff --git a/.prettierrc.json b/.prettierrc.json index 23de5df..e69de29 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,7 +0,0 @@ -{ - "semi": true, - "singleQuote": true, - "trailingComma": "all", - "printWidth": 120, - "proseWrap": "always" -} diff --git a/.yarnrc b/.yarnrc index 7cd45b8..e69de29 100644 --- a/.yarnrc +++ b/.yarnrc @@ -1,3 +0,0 @@ -save-prefix "^" ---install.audit true ---add.audit true diff --git a/.yarnrc.yml b/.yarnrc.yml new file mode 100644 index 0000000..e002c33 --- /dev/null +++ b/.yarnrc.yml @@ -0,0 +1,10 @@ +approvedGitRepositories: + - '**' + +compressionLevel: mixed + +enableGlobalCache: false + +enableHardenedMode: false + +nodeLinker: node-modules diff --git a/action.yml b/action.yml index 3b7b149..0959514 100644 --- a/action.yml +++ b/action.yml @@ -9,8 +9,7 @@ inputs: unityVersion: required: false default: 'auto' - description: - 'Version of unity to use for building the project. Use "auto" to get from your ProjectSettings/ProjectVersion.txt' + description: 'Version of unity to use for building the project. Use "auto" to get from your ProjectSettings/ProjectVersion.txt' customImage: required: false default: '' @@ -47,6 +46,10 @@ inputs: required: false default: '' description: 'Custom parameters to configure the build.' + useHostNetwork: + required: false + default: false + description: 'Initialises Docker using the host network. (Linux only)' versioning: required: false default: 'Semantic' @@ -104,11 +107,13 @@ inputs: gitPrivateToken: required: false default: '' - description: '[Orchestrator] Github private token to pull from github' - githubOwner: + description: 'Github private token to pull from github' + providerStrategy: + default: 'local' required: false - default: '' - description: '[Orchestrator] GitHub owner name or organization/team name' + description: + 'Build execution strategy. Use "local" for local Docker/Mac builds. For remote builds (aws, k8s, etc.), install + @game-ci/orchestrator and use the game-ci/orchestrator action which declares its own inputs.' runAsHostUser: required: false default: 'false' @@ -118,8 +123,7 @@ inputs: chownFilesTo: required: false default: '' - description: - 'User and optionally group (user or user:group or uid:gid) to give ownership of the resulting build artifacts' + description: 'User and optionally group (user or user:group or uid:gid) to give ownership of the resulting build artifacts' dockerCpuLimit: required: false default: '' @@ -149,102 +153,7 @@ inputs: allowDirtyBuild: required: false default: '' - description: '[Orchestrator] Allows the branch of the build to be dirty, and still generate the build.' - postBuildSteps: - required: false - default: '' - description: - '[Orchestrator] run a post build job in yaml format with the keys image, secrets (name, value object array), - command string' - preBuildSteps: - required: false - default: '' - description: - '[Orchestrator] Run a pre build job after the repository setup but before the build job (in yaml format with the - keys image, secrets (name, value object array), command line string)' - containerHookFiles: - required: false - default: '' - description: - '[Orchestrator] Specify the names (by file name) of custom steps to run before or after orchestrator jobs, must - match a yaml step file inside your repo in the folder .game-ci/steps/' - customHookFiles: - required: false - default: '' - description: - '[Orchestrator] Specify the names (by file name) of custom hooks to run before or after orchestrator jobs, must - match a yaml step file inside your repo in the folder .game-ci/hooks/' - customCommandHooks: - required: false - default: '' - description: '[Orchestrator] Specify custom commands and trigger hooks (injects commands into jobs)' - customJob: - required: false - default: '' - description: - '[Orchestrator] Run a custom job instead of the standard build automation for orchestrator (in yaml format with the - keys image, secrets (name, value object array), command line string)' - awsStackName: - default: 'game-ci' - required: false - description: '[Orchestrator] The Cloud Formation stack name that must be setup before using this option.' - providerStrategy: - default: 'local' - required: false - description: - '[Orchestrator] Either local, k8s or aws can be used to run builds on a remote cluster. Additional parameters must - be configured.' - resourceTracking: - default: 'false' - required: false - description: '[Orchestrator] Enable resource tracking logs for disk usage and allocation summaries.' - containerCpu: - default: '' - required: false - description: '[Orchestrator] Amount of CPU time to assign the remote build container' - containerMemory: - default: '' - required: false - description: '[Orchestrator] Amount of memory to assign the remote build container' - readInputFromOverrideList: - default: '' - required: false - description: '[Orchestrator] Comma separated list of input value names to read from "input override command"' - readInputOverrideCommand: - default: '' - required: false - description: - '[Orchestrator] Extend game ci by specifying a command to execute to pull input from external source e.g cloud - provider secret managers' - kubeConfig: - default: '' - required: false - description: - '[Orchestrator] Supply a base64 encoded kubernetes config to run builds on kubernetes and stream logs until - completion.' - kubeVolume: - default: '' - required: false - description: '[Orchestrator] Supply a Persistent Volume Claim name to use for the Unity build.' - kubeStorageClass: - default: '' - required: false - description: - '[Orchestrator] Kubernetes storage class to use for orchestrator jobs, leave empty to install rook cluster.' - kubeVolumeSize: - default: '5Gi' - required: false - description: '[Orchestrator] Amount of disc space to assign the Kubernetes Persistent Volume' - cacheKey: - default: '' - required: false - description: '[Orchestrator] Cache key to indicate bucket for cache' - watchToEnd: - default: 'true' - required: false - description: - '[Orchestrator] Whether or not to watch the build to the end. Can be used for especially long running jobs e.g - imports or self-hosted ephemeral runners.' + description: 'Allows the branch of the build to be dirty, and still generate the build.' cacheUnityInstallationOnMac: default: 'false' required: false @@ -269,16 +178,11 @@ inputs: default: 'false' required: false description: 'Skip the activation/deactivation of Unity. This assumes Unity is already activated.' - cloneDepth: - default: '50' - required: false - description: '[Orchestrator] Specifies the depth of the git clone for the repository. Use 0 for full clone.' - orchestratorRepoName: - default: 'step-security/unity-builder' + linux64RemoveExecutableExtension: + default: 'false' required: false description: - '[Orchestrator] Specifies the repo for the unity builder. Useful if you forked the repo for testing, features, or - fixes.' + 'When building for StandaloneLinux64, remove the default file extension of `.x86_64`. Set to true to restore the extensionless behavior from v4.' outputs: volume: diff --git a/cherry-pick.md b/cherry-pick.md new file mode 100644 index 0000000..56470ac --- /dev/null +++ b/cherry-pick.md @@ -0,0 +1,87 @@ +# Cherry-Pick Workflow + +## Context +PR: https://github.com/step-security/unity-builder/pull/30 + +This repository is a secure drop-in replacement for an upstream action. We cherry-pick selected changes from upstream while maintaining our own identity and release process. + +## Steps + +### 1. Read the Cherry-Pick Verification Report +- Open the PR above and find the comment posted by the GitHub Actions bot titled **"Cherry-Pick Verification Report"**. +- This report lists the two upstream versions being compared and indicates which commits have already been cherry-picked. +- Pay particular attention to these sections, which drive the manual passes: + - **Completely Skipped Commits** — commits that only touched paths the script ignores (`package.json`, `package-lock.json`, `yarn.lock`, `node_modules/`, `dist/`, `.gitignore`). Many of these still carry version bumps you must apply manually. + - **Conflicting Files** — files the script tried to apply but couldn't merge (commonly `README.md`, `package.json`, sometimes `.github/dependabot.yml`). + - **Missing Files** and **Workflow Files** — usually skipped per the rules below; verify before acting. + +### 2. Identify the upstream repository +- Go to the homepage of this repo. +- In the **About** section, you will see a description like *"Secure drop-in replacement for ..."* — the upstream repo name is in that description. +- Open the upstream repo and navigate to the comparison view between the two versions referenced in the report (e.g. `https://github.com//compare/v4.0.0...v4.1.0`). Reading the diff directly is the fastest way to design the manual edits. + +### 3. Cherry-pick the missing commits +Cherry-pick only the commits listed as **not yet done** in the verification report, applying the rules below. + +## Rules + +### Always cherry-pick +- **`README.md` and `package.json`** — these almost always show up under the report's *Conflicting Files* or *Completely Skipped Commits* sections. Apply the upstream delta manually, but **preserve our branding and identity**: the StepSecurity banner/badges in `README.md`, and `repository.url` + `author` + any step-security-specific deps (e.g. `@actions/github`, `axios` for the subscription/banner code) in `package.json`. +- **Version upgrades** of dependencies in `package.json` (even though `package.json`/`package-lock.json` aren't cherry-picked via script, version bumps from upstream should be brought over manually). +- **Build-toolchain migrations** — e.g. ncc → esbuild. Apply the new `build` script, add/remove the corresponding dev-deps (`@vercel/ncc` → `esbuild`, `generate-license-file`), and **delete the stale build artifacts from `dist/`** so the layout matches upstream (the bot's auto-update of `dist/` only adds the new file, it doesn't prune the old one). +- **ESM / module-system conversion changes** in `package.json` and related config files — e.g., adding `"type": "module"`, updating `test` scripts to point at the new `jest.config.cjs`, etc. When upstream converts the action to an ES module, bring those structural changes too, not just version bumps. +- **Renames driven by ESM conversion** — e.g., `jest.config.js` → `jest.config.cjs`. These show up in the bot's "Missing Files" list and must be applied to keep tests/build working. +- **Workflow file changes** — workflow files are never applied by the script, but they **are** listed in the report under *"Workflow Files (Cannot be auto-applied by GitHub Actions)"*. Walk through that list and, for each file that still exists in our repo, apply the upstream v(prev)…v(target) delta manually. The categories of change to bring over: + - **Plain version bumps** of `uses:` references (action major/minor/patch upgrades, including the pinned SHA + trailing `# v` comment). + - **`permissions:` blocks — do NOT pick blindly.** A bare `permissions: contents: read` is the default-ish read posture, and the workflow almost always runs fine without it being declared at all. Apply this rule: + - **Workflow change is only a new `permissions:` block, nothing else** → **skip**. No new step is asking for a token scope, so there's nothing to harden. Adding it is churn. + - **Workflow adds new steps that actually need a token scope** (e.g. a step that pushes commits, comments on PRs, uploads SARIF, writes packages, etc.) → bring the `permissions:` block over, but **only the scopes the new steps actually need**. Don't widen beyond that. + - **Upstream introduces any `write` scope** (`contents: write`, `pull-requests: write`, `id-token: write`, `security-events: write`, `packages: write`, etc.) → **double-check before applying**: which step needs it, is that step actually being adopted, and is there a less-privileged alternative? Default is to skip unless the corresponding step is also being cherry-picked. + - If our workflow already has a more restrictive `permissions:` block than upstream, keep ours. + - **Coordinated refactors that must be applied together** — whenever upstream bumps an action's major version alongside changes to the surrounding workflow (renamed step IDs, renamed job outputs, changed `with:` keys, changed matrix strategy, swapped subaction paths, etc.), treat the bump and the surrounding edits as one atomic change. Applying only the version bump without the surrounding edits — or vice versa — typically leaves the workflow broken. The way to spot these: read the upstream `compare/v(prev)...v(target)` diff for that workflow file and apply every hunk that touches it, not just the `uses:` line. + + When applying, **preserve our customizations**: the `step-security/harden-runner` pre-steps in every job, SHA-pinned action references with the `# v` trailing comment, our own concurrency/permissions settings if more restrictive than upstream, and any other step-security-specific wiring. Files that exist only in our repo (e.g. `actions_release.yml`) are still off-limits regardless of upstream changes. + +### Never cherry-pick +- **Author/maintainer name changes** — this project is maintained under our own name; do not import upstream branding or author references. In `package.json`, keep our `repository` field (`step-security/...`) and never overwrite it with upstream's value. +- **Markdown docs** like `CONTRIBUTING.md`, `CLAUDE.md`, `CHANGELOG.md`, and similar meta-docs. +- **Our own release process files** — e.g., `actions_release.yml` is ours; never overwrite it with upstream changes. The same applies to any other file that exists only in our repo. +- **Workflow files via script** — the automated script never touches workflow files; the report lists them under *"Workflow Files (Cannot be auto-applied by GitHub Actions)"* precisely so you handle them manually (see *Always cherry-pick → Workflow file changes* for what to apply). +- **Protected files — never update regardless of upstream changes.** These files are owned by step-security and must never be modified during cherry-pick, no matter what the upstream delta is: + - `.github/dependabot.yml` + - `.github/workflows/scorecards.yml` + - `.github/workflows/dependency-review.yml` + - `.github/workflows/claude_review.yml` + - `.github/workflows/codeql.yml` + - `.github/workflows/auto_cherry_pick.yml` + - `.github/workflows/audit_package.yml` + - `.github/workflows/actions_release.yml` + +### Use judgment +For files that exist in upstream but **not in our repo**, separate two cases — the right call is different in each: + +- **Pre-existing upstream file, never adopted in our repo** — e.g. a file that's existed upstream for many releases but isn't in our fork. This is almost always a deliberate past decision (skipped or deleted as unnecessary). Default: leave it out; don't reintroduce just because upstream changed it. +- **Newly introduced upstream file in this version range** — e.g. a workflow or config that upstream added between the previous and target versions. We've never had a chance to evaluate it. Default: assess on its own merits — does it duplicate something we already do (e.g. zizmor vs our existing CodeQL/Scorecards/audit workflows)? Is it consistent with how we maintain the other ~500 actions in the fleet? Only adopt it if the answer to both is "yes, and we'd want it fleet-wide" — otherwise skip, but flag it so the call is intentional rather than accidental. + +To tell which case you're in: check whether the path appears in the upstream tree at the **previous** version. If yes → pre-existing. If no → new in this range. + +## After cherry-picking +Verify locally. + +**First, detect the package manager and the actual script names** — don't assume `yarn build`/`yarn test`. The repo could use yarn, npm, or pnpm, and the scripts in `package.json` may not be named `build`/`test` (e.g. some repos use `bundle`, `compile`, `dist`, `vitest`, `jest`, etc.): + +- **Package manager** — check in this order: + - `yarn.lock` and/or `.yarnrc.yml` / `.yarn/` → use `yarn` + - `pnpm-lock.yaml` → use `pnpm` + - `package-lock.json` → use `npm` + - Fall back to `package.json`'s `packageManager` field if no lockfile is obvious. +- **Script names** — read `package.json`'s `scripts` block. Pick the script that actually produces `dist/` for "build" (look for `ncc`, `esbuild`, `tsc`, `rollup`, etc.) and the script that runs the test suite for "test" (look for `vitest`, `jest`, `mocha`, etc.). If the script is named differently from `build`/`test`, use the real name. + +Then run, using the detected tool and scripts: + +1. ` install` — regenerates the lockfile to match any `package.json` changes. +2. ` run ` — regenerates `dist/` with the new toolchain. Confirm `dist/` ends up with the same file set as upstream (extra build artifacts from the old toolchain must be removed by hand). +3. ` run ` — runs the test suite to confirm the new bundle and dep bumps work. +4. `git status` — confirm only the intended files changed. + +**Do NOT commit.** Stop after verification and hand off to the user — they will review the diff and commit themselves. Also do not stage `cherry-pick.md`; it's a working note, not part of the action. \ No newline at end of file diff --git a/community-plugins.yml b/community-plugins.yml new file mode 100644 index 0000000..45a028b --- /dev/null +++ b/community-plugins.yml @@ -0,0 +1,27 @@ +# Community Plugin Validation Registry +# Packages listed here are automatically tested on a schedule +# to ensure compatibility with unity-builder. +# +# Format: +# - name: Human-readable name +# package: UPM package name or git URL +# source: upm | git | asset-store +# unity: Minimum Unity version (optional, defaults to 2021.3) +# platforms: List of platforms to test (optional, defaults to [StandaloneLinux64]) +# timeout: Build timeout in minutes (optional, defaults to 30) + +plugins: + # Example entries — community members can submit PRs to add their packages + - name: UniTask + package: https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask + source: git + platforms: [StandaloneLinux64, StandaloneWindows64] + + - name: NaughtyAttributes + package: https://github.com/dbrizov/NaughtyAttributes.git?path=Assets/NaughtyAttributes + source: git + + - name: Unity Atoms + package: https://github.com/unity-atoms/unity-atoms.git + source: git + platforms: [StandaloneLinux64] diff --git a/dist/index.js b/dist/index.js index b5bff17..b8c660d 100644 --- a/dist/index.js +++ b/dist/index.js @@ -33,24 +33,25 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.runMain = void 0; const core = __importStar(__nccwpck_require__(42186)); const github = __importStar(__nccwpck_require__(95438)); const axios_1 = __importStar(__nccwpck_require__(88757)); const model_1 = __nccwpck_require__(41359); -const cli_1 = __nccwpck_require__(55651); const mac_builder_1 = __importDefault(__nccwpck_require__(39364)); const platform_setup_1 = __importDefault(__nccwpck_require__(64423)); +const plugin_1 = __nccwpck_require__(67270); async function validateSubscription() { const repoPrivate = github.context?.payload?.repository?.private; const upstream = 'game-ci/unity-builder'; const action = process.env.GITHUB_ACTION_REPOSITORY; const docsUrl = 'https://docs.stepsecurity.io/actions/stepsecurity-maintained-actions'; core.info(''); - core.info('\u001b[1;36mStepSecurity Maintained Action\u001b[0m'); + core.info('StepSecurity Maintained Action'); core.info(`Secure drop-in replacement for ${upstream}`); if (repoPrivate === false) - core.info('\u001b[32m\u2713 Free for public repositories\u001b[0m'); - core.info(`\u001b[36mLearn more:\u001b[0m ${docsUrl}`); + core.info('✓ Free for public repositories'); + core.info(`Learn more: ${docsUrl}`); core.info(''); if (repoPrivate === false) return; @@ -63,46 +64,47 @@ async function validateSubscription() { } catch (error) { if ((0, axios_1.isAxiosError)(error) && error.response?.status === 403) { - core.error(`\u001b[1;31mThis action requires a StepSecurity subscription for private repositories.\u001b[0m`); - core.error(`\u001b[31mLearn how to enable a subscription: ${docsUrl}\u001b[0m`); + core.error(`This action requires a StepSecurity subscription for private repositories.`); + core.error(`Learn how to enable a subscription: ${docsUrl}`); process.exit(1); } core.info('Timeout or API not reachable. Continuing to next step.'); } } +// Exported so tests can drive the lifecycle directly without depending on +// vitest's module re-loading (which changed in vitest 4). async function runMain() { try { await validateSubscription(); - if (cli_1.Cli.InitCliMode()) { - await cli_1.Cli.RunCli(); - return; - } model_1.Action.checkCompatibility(); model_1.Cache.verify(); const { workspace, actionFolder } = model_1.Action; const buildParameters = await model_1.BuildParameters.create(); const baseImage = new model_1.ImageTag(buildParameters); + // Load optional plugin. The default implementation is @game-ci/orchestrator. + const plugin = await (0, plugin_1.loadPlugin)(); + await plugin?.initialize(buildParameters, workspace); let exitCode = -1; - if (buildParameters.providerStrategy === 'local') { - core.info('Building locally'); - await platform_setup_1.default.setup(buildParameters, actionFolder); - exitCode = - process.platform === 'darwin' - ? await mac_builder_1.default.run(actionFolder) - : await model_1.Docker.run(baseImage.toString(), { - workspace, - actionFolder, - ...buildParameters, - }); + if (plugin?.canHandleBuild()) { + // Plugin handles the build entirely (remote providers, hot runner, test workflows) + const result = await plugin.handleBuild(baseImage.toString()); + exitCode = result.fallbackToLocal + ? await runLocalBuild(buildParameters, baseImage, workspace, actionFolder, plugin) + : result.exitCode; + } + else if (buildParameters.providerStrategy === 'local') { + exitCode = await runLocalBuild(buildParameters, baseImage, workspace, actionFolder, plugin); } else { - await model_1.Orchestrator.run(buildParameters, baseImage.toString()); - exitCode = 0; + throw new Error(`Provider strategy "${buildParameters.providerStrategy}" requires @game-ci/orchestrator. ` + + 'Install it via the game-ci/orchestrator action, or use providerStrategy=local.'); } - // Set output + // Set core outputs await model_1.Output.setBuildVersion(buildParameters.buildVersion); await model_1.Output.setAndroidVersionCode(buildParameters.androidVersionCode); await model_1.Output.setEngineExitCode(exitCode); + // Plugin handles post-build (artifacts, archiving, retention) + await plugin?.handlePostBuild(exitCode); if (exitCode !== 0) { core.setFailed(`Build failed with exit code ${exitCode}`); } @@ -111,7 +113,26 @@ async function runMain() { core.setFailed(error.message); } } -runMain(); +exports.runMain = runMain; +async function runLocalBuild(buildParameters, baseImage, workspace, actionFolder, plugin) { + await plugin?.beforeLocalBuild(workspace); + await platform_setup_1.default.setup(buildParameters, actionFolder); + const exitCode = process.platform === 'darwin' + ? await mac_builder_1.default.run(actionFolder) + : await model_1.Docker.run(baseImage.toString(), { + workspace, + actionFolder, + ...buildParameters, + }); + await plugin?.afterLocalBuild(workspace, exitCode); + return exitCode; +} +// Auto-run when this module is the entry point. Tests import the file via +// `await import('./index')` purely to register the mock factories and then +// call `runMain()` directly. +if (process.env.NODE_ENV !== 'test') { + runMain(); +} /***/ }), @@ -267,25 +288,68 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); const nanoid_1 = __nccwpck_require__(17592); const android_versioning_1 = __importDefault(__nccwpck_require__(43059)); -const orchestrator_constants_1 = __importDefault(__nccwpck_require__(47214)); -const orchestrator_guid_1 = __importDefault(__nccwpck_require__(38612)); const input_1 = __importDefault(__nccwpck_require__(48096)); const platform_1 = __importDefault(__nccwpck_require__(9707)); const unity_versioning_1 = __importDefault(__nccwpck_require__(17146)); const versioning_1 = __importDefault(__nccwpck_require__(88729)); const git_repo_1 = __nccwpck_require__(24271); const github_cli_1 = __nccwpck_require__(44990); -const cli_1 = __nccwpck_require__(55651); +const plugin_options_1 = __nccwpck_require__(77038); const github_1 = __importDefault(__nccwpck_require__(83654)); -const orchestrator_options_1 = __importDefault(__nccwpck_require__(82473)); -const orchestrator_1 = __importDefault(__nccwpck_require__(8330)); const core = __importStar(__nccwpck_require__(42186)); class BuildParameters { - static shouldUseRetainedWorkspaceMode(buildParameters) { - return buildParameters.maxRetainedWorkspaces > 0 && orchestrator_1.default.lockedWorkspace !== ``; - } + editorVersion; + customImage; + unitySerial; + unityLicensingServer; + skipActivation; + runnerTempPath; + targetPlatform; + projectPath; + buildProfile; + buildName; + buildPath; + buildFile; + buildMethod; + buildVersion; + manualExit; + enableGpu; + androidVersionCode; + androidKeystoreName; + androidKeystoreBase64; + androidKeystorePass; + androidKeyaliasName; + androidKeyaliasPass; + androidTargetSdkVersion; + androidSdkManagerParameters; + androidExportType; + androidSymbolType; + dockerCpuLimit; + dockerMemoryLimit; + dockerIsolationMode; + containerRegistryRepository; + containerRegistryImageVersion; + customParameters; + useHostNetwork; + sshAgent; + sshPublicKeysDirectoryPath; + providerStrategy; + gitPrivateToken; + runAsHostUser; + chownFilesTo; + runNumber; + branch; + githubRepo; + gitSha; + logId; + buildGuid; + buildPlatform; + isCliMode; + cacheUnityInstallationOnMac; + unityHubVersionOnMac; + dockerWorkspacePath; static async create() { - const buildFile = this.parseBuildFile(input_1.default.buildName, input_1.default.targetPlatform, input_1.default.androidExportType); + const buildFile = this.parseBuildFile(input_1.default.buildName, input_1.default.targetPlatform, input_1.default.androidExportType, input_1.default.linux64RemoveExecutableExtension); const editorVersion = unity_versioning_1.default.determineUnityVersion(input_1.default.projectPath, input_1.default.unityVersion); const buildVersion = await versioning_1.default.determineBuildVersion(input_1.default.versioningStrategy, input_1.default.specifiedVersion); const androidVersionCode = android_versioning_1.default.determineVersionCode(buildVersion, input_1.default.androidVersionCode); @@ -321,6 +385,7 @@ class BuildParameters { core.setSecret(unitySerial); core.setSecret(`${unitySerial.slice(0, -4)}XXXX`); } + const providerStrategy = input_1.default.getInput('providerStrategy') || (plugin_options_1.PluginOptions.isPluginMode ? 'aws' : 'local'); return { editorVersion, customImage: input_1.default.customImage, @@ -349,6 +414,7 @@ class BuildParameters { androidExportType: input_1.default.androidExportType, androidSymbolType: androidSymbolExportType, customParameters: input_1.default.customParameters, + useHostNetwork: input_1.default.useHostNetwork, sshAgent: input_1.default.sshAgent, sshPublicKeysDirectoryPath: input_1.default.sshPublicKeysDirectoryPath, gitPrivateToken: input_1.default.gitPrivateToken ?? (await github_cli_1.GithubCliReader.GetGitHubAuthToken()), @@ -359,58 +425,21 @@ class BuildParameters { dockerIsolationMode: input_1.default.dockerIsolationMode, containerRegistryRepository: input_1.default.containerRegistryRepository, containerRegistryImageVersion: input_1.default.containerRegistryImageVersion, - providerStrategy: orchestrator_options_1.default.providerStrategy, - buildPlatform: orchestrator_options_1.default.buildPlatform, - kubeConfig: orchestrator_options_1.default.kubeConfig, - containerMemory: orchestrator_options_1.default.containerMemory, - containerCpu: orchestrator_options_1.default.containerCpu, - containerNamespace: orchestrator_options_1.default.containerNamespace, - kubeVolumeSize: orchestrator_options_1.default.kubeVolumeSize, - kubeVolume: orchestrator_options_1.default.kubeVolume, - postBuildContainerHooks: orchestrator_options_1.default.postBuildContainerHooks, - preBuildContainerHooks: orchestrator_options_1.default.preBuildContainerHooks, - customJob: orchestrator_options_1.default.customJob, + providerStrategy, + buildPlatform: providerStrategy !== 'local' ? 'linux' : process.platform, runNumber: input_1.default.runNumber, branch: input_1.default.branch.replace('/head', '') || (await git_repo_1.GitRepoReader.GetBranch()), - orchestratorBranch: orchestrator_options_1.default.orchestratorBranch.split('/').reverse()[0], - orchestratorDebug: orchestrator_options_1.default.orchestratorDebug, - githubRepo: (input_1.default.githubRepo ?? (await git_repo_1.GitRepoReader.GetRemote())) || orchestrator_options_1.default.orchestratorRepoName, - orchestratorRepoName: orchestrator_options_1.default.orchestratorRepoName, - cloneDepth: Number.parseInt(orchestrator_options_1.default.cloneDepth), - isCliMode: cli_1.Cli.isCliMode, - awsStackName: orchestrator_options_1.default.awsStackName, - awsEndpoint: orchestrator_options_1.default.awsEndpoint, - awsCloudFormationEndpoint: orchestrator_options_1.default.awsCloudFormationEndpoint, - awsEcsEndpoint: orchestrator_options_1.default.awsEcsEndpoint, - awsKinesisEndpoint: orchestrator_options_1.default.awsKinesisEndpoint, - awsCloudWatchLogsEndpoint: orchestrator_options_1.default.awsCloudWatchLogsEndpoint, - awsS3Endpoint: orchestrator_options_1.default.awsS3Endpoint, - storageProvider: orchestrator_options_1.default.storageProvider, - rcloneRemote: orchestrator_options_1.default.rcloneRemote, + githubRepo: (input_1.default.githubRepo ?? (await git_repo_1.GitRepoReader.GetRemote())) || 'game-ci/unity-builder', gitSha: input_1.default.gitSha, - logId: (0, nanoid_1.customAlphabet)(orchestrator_constants_1.default.alphabet, 9)(), - buildGuid: orchestrator_guid_1.default.generateGuid(input_1.default.runNumber, input_1.default.targetPlatform), - commandHooks: orchestrator_options_1.default.commandHooks, - inputPullCommand: orchestrator_options_1.default.inputPullCommand, - pullInputList: orchestrator_options_1.default.pullInputList, - kubeStorageClass: orchestrator_options_1.default.kubeStorageClass, - cacheKey: orchestrator_options_1.default.cacheKey, - maxRetainedWorkspaces: Number.parseInt(orchestrator_options_1.default.maxRetainedWorkspaces), - useLargePackages: orchestrator_options_1.default.useLargePackages, - useCompressionStrategy: orchestrator_options_1.default.useCompressionStrategy, - garbageMaxAge: orchestrator_options_1.default.garbageMaxAge, - githubChecks: orchestrator_options_1.default.githubChecks, - asyncWorkflow: orchestrator_options_1.default.asyncOrchestrator, - githubCheckId: orchestrator_options_1.default.githubCheckId, - finalHooks: orchestrator_options_1.default.finalHooks, - skipLfs: orchestrator_options_1.default.skipLfs, - skipCache: orchestrator_options_1.default.skipCache, + logId: (0, nanoid_1.customAlphabet)('0123456789abcdefghijklmnopqrstuvwxyz', 9)(), + buildGuid: `${input_1.default.runNumber}-${input_1.default.targetPlatform.toLowerCase().replace('standalone', '')}-${(0, nanoid_1.customAlphabet)('0123456789abcdefghijklmnopqrstuvwxyz', 4)()}`, + isCliMode: plugin_options_1.PluginOptions.isPluginMode, cacheUnityInstallationOnMac: input_1.default.cacheUnityInstallationOnMac, unityHubVersionOnMac: input_1.default.unityHubVersionOnMac, dockerWorkspacePath: input_1.default.dockerWorkspacePath, }; } - static parseBuildFile(filename, platform, androidExportType) { + static parseBuildFile(filename, platform, androidExportType, linux64RemoveExecutableExtension) { if (platform_1.default.isWindows(platform)) { return `${filename}.exe`; } @@ -426,6 +455,9 @@ class BuildParameters { throw new Error(`Unknown Android Export Type: ${androidExportType}. Must be one of androidPackage for apk, androidAppBundle for aab, androidStudioProject for android project`); } } + if (platform === platform_1.default.types.StandaloneLinux64 && !linux64RemoveExecutableExtension) { + return `${filename}.x86_64`; + } return filename; } static getSerialFromLicenseFile(license) { @@ -501,254 +533,6 @@ class Cache { exports["default"] = Cache; -/***/ }), - -/***/ 85301: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CliFunction = exports.CliFunctionsRepository = void 0; -class CliFunctionsRepository { - static PushCliFunction(target, propertyKey, descriptor, key, description) { - CliFunctionsRepository.targets.push({ - target, - propertyKey, - descriptor, - key, - description, - }); - } - static GetCliFunctions(key) { - const results = CliFunctionsRepository.targets.find((x) => x.key === key); - if (results === undefined || results.length === 0) { - throw new Error(`no CLI mode found for ${key}`); - } - return results; - } - static GetAllCliModes() { - return CliFunctionsRepository.targets.map((x) => { - return { - key: x.key, - description: x.description, - }; - }); - } - // eslint-disable-next-line no-unused-vars - static PushCliFunctionSource(cliFunction) { } -} -exports.CliFunctionsRepository = CliFunctionsRepository; -CliFunctionsRepository.targets = []; -function CliFunction(key, description) { - return (target, propertyKey, descriptor) => { - CliFunctionsRepository.PushCliFunction(target, propertyKey, descriptor, key, description); - }; -} -exports.CliFunction = CliFunction; - - -/***/ }), - -/***/ 55651: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Cli = void 0; -const commander_ts_1 = __nccwpck_require__(40451); -const __1 = __nccwpck_require__(41359); -const core = __importStar(__nccwpck_require__(42186)); -const action_yaml_1 = __nccwpck_require__(11091); -const orchestrator_logger_1 = __importDefault(__nccwpck_require__(32549)); -const orchestrator_query_override_1 = __importDefault(__nccwpck_require__(34664)); -const cli_functions_repository_1 = __nccwpck_require__(85301); -const caching_1 = __nccwpck_require__(6435); -const lfs_hashing_1 = __nccwpck_require__(23451); -const remote_client_1 = __nccwpck_require__(85666); -const orchestrator_options_reader_1 = __importDefault(__nccwpck_require__(54381)); -const github_1 = __importDefault(__nccwpck_require__(83654)); -class Cli { - static get isCliMode() { - return Cli.options !== undefined && Cli.options.mode !== undefined && Cli.options.mode !== ''; - } - static query(key, alternativeKey) { - if (Cli.options && Cli.options[key] !== undefined) { - return Cli.options[key]; - } - if (Cli.options && alternativeKey && Cli.options[alternativeKey] !== undefined) { - return Cli.options[alternativeKey]; - } - return; - } - static InitCliMode() { - cli_functions_repository_1.CliFunctionsRepository.PushCliFunctionSource(remote_client_1.RemoteClient); - cli_functions_repository_1.CliFunctionsRepository.PushCliFunctionSource(caching_1.Caching); - cli_functions_repository_1.CliFunctionsRepository.PushCliFunctionSource(lfs_hashing_1.LfsHashing); - const program = new commander_ts_1.Command(); - program.version('0.0.1'); - const properties = orchestrator_options_reader_1.default.GetProperties(); - const actionYamlReader = new action_yaml_1.ActionYamlReader(); - for (const element of properties) { - program.option(`--${element} <${element}>`, actionYamlReader.GetActionYamlValue(element)); - } - program.option('-m, --mode ', cli_functions_repository_1.CliFunctionsRepository.GetAllCliModes() - .map((x) => `${x.key} (${x.description})`) - .join(` | `)); - program.option('--populateOverride ', 'should use override query to pull input false by default'); - program.option('--cachePushFrom ', 'cache push from source folder'); - program.option('--cachePushTo ', 'cache push to caching folder'); - program.option('--artifactName ', 'caching artifact name'); - program.option('--select `).join('\n'); - - return ` - - Requesting Authorization - - -
- ${formInputs} -
- -`; - } - - /** - * @name endSessionUrl - * @api public - */ - endSessionUrl(params = {}) { - assertIssuerConfiguration(this.issuer, 'end_session_endpoint'); - - const { - 0: postLogout, - length, - } = this.post_logout_redirect_uris || []; - - const { - post_logout_redirect_uri = length === 1 ? postLogout : undefined, - } = params; - - let hint = params.id_token_hint; - - if (hint instanceof TokenSet) { - if (!hint.id_token) { - throw new TypeError('id_token not present in TokenSet'); - } - hint = hint.id_token; - } - - const target = url.parse(this.issuer.end_session_endpoint, true); - target.search = null; - target.query = { - ...params, - ...target.query, - ...{ - post_logout_redirect_uri, - id_token_hint: hint, - }, - }; - - Object.entries(target.query).forEach(([key, value]) => { - if (value === null || value === undefined) { - delete target.query[key]; - } - }); - - return url.format(target); - } - - /** - * @name callbackParams - * @api public - */ - callbackParams(input) { // eslint-disable-line class-methods-use-this - const isIncomingMessage = input instanceof stdhttp.IncomingMessage - || (input && input.method && input.url); - const isString = typeof input === 'string'; - - if (!isString && !isIncomingMessage) { - throw new TypeError('#callbackParams only accepts string urls, http.IncomingMessage or a lookalike'); - } - - if (isIncomingMessage) { - switch (input.method) { - case 'GET': - return pickCb(url.parse(input.url, true).query); - case 'POST': - if (input.body === undefined) { - throw new TypeError('incoming message body missing, include a body parser prior to this method call'); - } - switch (typeof input.body) { - case 'object': - case 'string': - if (Buffer.isBuffer(input.body)) { - return pickCb(querystring.parse(input.body.toString('utf-8'))); - } - if (typeof input.body === 'string') { - return pickCb(querystring.parse(input.body)); - } - - return pickCb(input.body); - default: - throw new TypeError('invalid IncomingMessage body object'); - } - default: - throw new TypeError('invalid IncomingMessage method'); - } - } else { - return pickCb(url.parse(input, true).query); - } - } - - /** - * @name callback - * @api public - */ - async callback( - redirectUri, - parameters, - checks = {}, - { exchangeBody, clientAssertionPayload, DPoP } = {}, - ) { - let params = pickCb(parameters); - - if (checks.jarm && !('response' in parameters)) { - throw new RPError({ - message: 'expected a JARM response', - checks, - params, - }); - } else if ('response' in parameters) { - const decrypted = await this.decryptJARM(params.response); - params = await this.validateJARM(decrypted); - } - - if (this.default_max_age && !checks.max_age) { - checks.max_age = this.default_max_age; - } - - if (params.state && !checks.state) { - throw new TypeError('checks.state argument is missing'); - } - - if (!params.state && checks.state) { - throw new RPError({ - message: 'state missing from the response', - checks, - params, - }); - } - - if (checks.state !== params.state) { - throw new RPError({ - printf: ['state mismatch, expected %s, got: %s', checks.state, params.state], - checks, - params, - }); - } - - if (params.error) { - throw new OPError(params); - } - - const RESPONSE_TYPE_REQUIRED_PARAMS = { - code: ['code'], - id_token: ['id_token'], - token: ['access_token', 'token_type'], - }; - - if (checks.response_type) { - for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax - if (type === 'none') { - if (params.code || params.id_token || params.access_token) { - throw new RPError({ - message: 'unexpected params encountered for "none" response', - checks, - params, - }); - } - } else { - for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len - if (!params[param]) { - throw new RPError({ - message: `${param} missing from response`, - checks, - params, - }); +class ContainerClient extends StorageClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + let pipeline; + let url; + options = options || {}; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + const containerName = credentialOrPipelineOrContainerName; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreHttp.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + if (!options.proxyOptions) { + options.proxyOptions = coreHttp.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") { + url = + 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"); } - } } - } - } - - if (params.id_token) { - const tokenset = new TokenSet(params); - await this.decryptIdToken(tokenset); - await this.validateIdToken(tokenset, checks.nonce, 'authorization', checks.max_age, checks.state); - - if (!params.code) { - return tokenset; - } - } - - if (params.code) { - const tokenset = await this.grant({ - ...exchangeBody, - grant_type: 'authorization_code', - code: params.code, - redirect_uri: redirectUri, - code_verifier: checks.code_verifier, - }, { clientAssertionPayload, DPoP }); - - await this.decryptIdToken(tokenset); - await this.validateIdToken(tokenset, checks.nonce, 'token', checks.max_age); - - if (params.session_state) { - tokenset.session_state = params.session_state; - } - - return tokenset; - } - - return new TokenSet(params); - } - - /** - * @name oauthCallback - * @api public - */ - async oauthCallback( - redirectUri, - parameters, - checks = {}, - { exchangeBody, clientAssertionPayload, DPoP } = {}, - ) { - let params = pickCb(parameters); - - if (checks.jarm && !('response' in parameters)) { - throw new RPError({ - message: 'expected a JARM response', - checks, - params, - }); - } else if ('response' in parameters) { - const decrypted = await this.decryptJARM(params.response); - params = await this.validateJARM(decrypted); - } - - if (params.state && !checks.state) { - throw new TypeError('checks.state argument is missing'); - } - - if (!params.state && checks.state) { - throw new RPError({ - message: 'state missing from the response', - checks, - params, - }); - } - - if (checks.state !== params.state) { - throw new RPError({ - printf: ['state mismatch, expected %s, got: %s', checks.state, params.state], - checks, - params, - }); + else { + throw new Error("Expecting non-empty strings for containerName parameter"); + } + super(url, pipeline); + this._containerName = this.getContainerNameFromUrl(); + this.containerContext = new Container(this.storageClientContext); } - - if (params.error) { - throw new OPError(params); + /** + * The name of the container. + */ + get containerName() { + return this._containerName; } - - const RESPONSE_TYPE_REQUIRED_PARAMS = { - code: ['code'], - token: ['access_token', 'token_type'], - }; - - if (checks.response_type) { - for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax - if (type === 'none') { - if (params.code || params.id_token || params.access_token) { - throw new RPError({ - message: 'unexpected params encountered for "none" response', - checks, - params, + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-create", options); + try { + // Spread operator in destructuring assignments, + // this will filter out unwanted properties from the response object into result object + return await this.containerContext.create(Object.assign(Object.assign({}, options), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, }); - } + throw e; } - - if (RESPONSE_TYPE_REQUIRED_PARAMS[type]) { - for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len - if (!params[param]) { - throw new RPError({ - message: `${param} missing from response`, - checks, - params, - }); - } - } + finally { + span.end(); } - } - } - - if (params.code) { - return this.grant({ - ...exchangeBody, - grant_type: 'authorization_code', - code: params.code, - redirect_uri: redirectUri, - code_verifier: checks.code_verifier, - }, { clientAssertionPayload, DPoP }); - } - - return new TokenSet(params); - } - - /** - * @name decryptIdToken - * @api private - */ - async decryptIdToken(token) { - if (!this.id_token_encrypted_response_alg) { - return token; - } - - let idToken = token; - - if (idToken instanceof TokenSet) { - if (!idToken.id_token) { - throw new TypeError('id_token not present in TokenSet'); - } - idToken = idToken.id_token; - } - - const expectedAlg = this.id_token_encrypted_response_alg; - const expectedEnc = this.id_token_encrypted_response_enc; - - const result = await this.decryptJWE(idToken, expectedAlg, expectedEnc); - - if (token instanceof TokenSet) { - token.id_token = result; - return token; - } - - return result; - } - - async validateJWTUserinfo(body) { - const expectedAlg = this.userinfo_signed_response_alg; - - return this.validateJWT(body, expectedAlg, []); - } - - /** - * @name decryptJARM - * @api private - */ - async decryptJARM(response) { - if (!this.authorization_encrypted_response_alg) { - return response; - } - - const expectedAlg = this.authorization_encrypted_response_alg; - const expectedEnc = this.authorization_encrypted_response_enc; - - return this.decryptJWE(response, expectedAlg, expectedEnc); - } - - /** - * @name decryptJWTUserinfo - * @api private - */ - async decryptJWTUserinfo(body) { - if (!this.userinfo_encrypted_response_alg) { - return body; - } - - const expectedAlg = this.userinfo_encrypted_response_alg; - const expectedEnc = this.userinfo_encrypted_response_enc; - - return this.decryptJWE(body, expectedAlg, expectedEnc); - } - - /** - * @name decryptJWE - * @api private - */ - async decryptJWE(jwe, expectedAlg, expectedEnc = 'A128CBC-HS256') { - const header = JSON.parse(base64url.decode(jwe.split('.')[0])); - - if (header.alg !== expectedAlg) { - throw new RPError({ - printf: ['unexpected JWE alg received, expected %s, got: %s', expectedAlg, header.alg], - jwt: jwe, - }); } - - if (header.enc !== expectedEnc) { - throw new RPError({ - printf: ['unexpected JWE enc received, expected %s, got: %s', expectedEnc, header.enc], - jwt: jwe, - }); - } - - let keyOrStore; - - if (expectedAlg.match(/^(?:RSA|ECDH)/)) { - keyOrStore = instance(this).get('keystore'); - } else { - keyOrStore = await this.joseSecret(expectedAlg === 'dir' ? expectedEnc : expectedAlg); - } - - const payload = jose.JWE.decrypt(jwe, keyOrStore); - return payload.toString('utf8'); - } - - /** - * @name validateIdToken - * @api private - */ - async validateIdToken(tokenSet, nonce, returnedBy, maxAge, state) { - let idToken = tokenSet; - - const expectedAlg = this.id_token_signed_response_alg; - - const isTokenSet = idToken instanceof TokenSet; - - if (isTokenSet) { - if (!idToken.id_token) { - throw new TypeError('id_token not present in TokenSet'); - } - idToken = idToken.id_token; - } - - idToken = String(idToken); - - const timestamp = now(); - const { protected: header, payload, key } = await this.validateJWT(idToken, expectedAlg); - - if (maxAge || (maxAge !== null && this.require_auth_time)) { - if (!payload.auth_time) { - throw new RPError({ - message: 'missing required JWT property auth_time', - jwt: idToken, - }); - } - if (typeof payload.auth_time !== 'number') { - throw new RPError({ - message: 'JWT auth_time claim must be a JSON numeric value', - jwt: idToken, - }); - } - } - - if (maxAge && (payload.auth_time + maxAge < timestamp - this[CLOCK_TOLERANCE])) { - throw new RPError({ - printf: ['too much time has elapsed since the last End-User authentication, max_age %i, auth_time: %i, now %i', maxAge, payload.auth_time, timestamp - this[CLOCK_TOLERANCE]], - now: timestamp, - tolerance: this[CLOCK_TOLERANCE], - auth_time: payload.auth_time, - jwt: idToken, - }); - } - - if (nonce !== null && (payload.nonce || nonce !== undefined) && payload.nonce !== nonce) { - throw new RPError({ - printf: ['nonce mismatch, expected %s, got: %s', nonce, payload.nonce], - jwt: idToken, - }); + /** + * 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 = {}) { + var _a, _b; + const { span, updatedOptions } = createSpan("ContainerClient-createIfNotExists", options); + 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") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when creating a container only if it does not already exist.", + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - - const fapi = this.constructor.name === 'FAPIClient'; - - if (returnedBy === 'authorization') { - if (!payload.at_hash && tokenSet.access_token) { - throw new RPError({ - message: 'missing required property at_hash', - jwt: idToken, - }); - } - - if (!payload.c_hash && tokenSet.code) { - throw new RPError({ - message: 'missing required property c_hash', - jwt: idToken, - }); - } - - if (fapi) { - if (!payload.s_hash && (tokenSet.state || state)) { - throw new RPError({ - message: 'missing required property s_hash', - jwt: idToken, - }); + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-exists", options); + try { + await this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions, + }); + return true; } - } - - if (payload.s_hash) { - if (!state) { - throw new TypeError('cannot verify s_hash, "checks.state" property not provided'); + catch (e) { + if (e.statusCode === 404) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when checking container existence", + }); + return false; + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; } - - try { - tokenHash.validate({ claim: 's_hash', source: 'state' }, payload.s_hash, state, header.alg, key && key.crv); - } catch (err) { - throw new RPError({ message: err.message, jwt: idToken }); + finally { + span.end(); } - } - } - - if (fapi && payload.iat < timestamp - 3600) { - throw new RPError({ - printf: ['JWT issued too far in the past, now %i, iat %i', timestamp, payload.iat], - now: timestamp, - tolerance: this[CLOCK_TOLERANCE], - iat: payload.iat, - jwt: idToken, - }); - } - - if (tokenSet.access_token && payload.at_hash !== undefined) { - try { - tokenHash.validate({ claim: 'at_hash', source: 'access_token' }, payload.at_hash, tokenSet.access_token, header.alg, key && key.crv); - } catch (err) { - throw new RPError({ message: err.message, jwt: idToken }); - } - } - - if (tokenSet.code && payload.c_hash !== undefined) { - try { - tokenHash.validate({ claim: 'c_hash', source: 'code' }, payload.c_hash, tokenSet.code, header.alg, key && key.crv); - } catch (err) { - throw new RPError({ message: err.message, jwt: idToken }); - } - } - - return tokenSet; - } - - /** - * @name validateJWT - * @api private - */ - async validateJWT(jwt, expectedAlg, required = ['iss', 'sub', 'aud', 'exp', 'iat']) { - const isSelfIssued = this.issuer.issuer === 'https://self-issued.me'; - const timestamp = now(); - let header; - let payload; - try { - ({ header, payload } = jose.JWT.decode(jwt, { complete: true })); - } catch (err) { - throw new RPError({ - printf: ['failed to decode JWT (%s: %s)', err.name, err.message], - jwt, - }); - } - - if (header.alg !== expectedAlg) { - throw new RPError({ - printf: ['unexpected JWT alg received, expected %s, got: %s', expectedAlg, header.alg], - jwt, - }); - } - - if (isSelfIssued) { - required = [...required, 'sub_jwk']; // eslint-disable-line no-param-reassign } - - required.forEach(verifyPresence.bind(undefined, payload, jwt)); - - if (payload.iss !== undefined) { - let expectedIss = this.issuer.issuer; - - if (aadIssValidation) { - expectedIss = this.issuer.issuer.replace('{tenantid}', payload.tid); - } - - if (payload.iss !== expectedIss) { - throw new RPError({ - printf: ['unexpected iss value, expected %s, got: %s', expectedIss, payload.iss], - jwt, - }); - } + /** + * 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); } - - if (payload.iat !== undefined) { - if (typeof payload.iat !== 'number') { - throw new RPError({ - message: 'JWT iat claim must be a JSON numeric value', - jwt, - }); - } + /** + * Creates an {@link AppendBlobClient} + * + * @param blobName - An append blob name + */ + getAppendBlobClient(blobName) { + return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } - - if (payload.nbf !== undefined) { - if (typeof payload.nbf !== 'number') { - throw new RPError({ - message: 'JWT nbf claim must be a JSON numeric value', - jwt, - }); - } - if (payload.nbf > timestamp + this[CLOCK_TOLERANCE]) { - throw new RPError({ - printf: ['JWT not active yet, now %i, nbf %i', timestamp + this[CLOCK_TOLERANCE], payload.nbf], - now: timestamp, - tolerance: this[CLOCK_TOLERANCE], - nbf: payload.nbf, - jwt, - }); - } + /** + * 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); } - - if (payload.exp !== undefined) { - if (typeof payload.exp !== 'number') { - throw new RPError({ - message: 'JWT exp claim must be a JSON numeric value', - jwt, - }); - } - if (timestamp - this[CLOCK_TOLERANCE] >= payload.exp) { - throw new RPError({ - printf: ['JWT expired, now %i, exp %i', timestamp - this[CLOCK_TOLERANCE], payload.exp], - now: timestamp, - tolerance: this[CLOCK_TOLERANCE], - exp: payload.exp, - jwt, - }); - } + /** + * Creates a {@link PageBlobClient} + * + * @param blobName - A page blob name + */ + getPageBlobClient(blobName) { + return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } - - if (payload.aud !== undefined) { - if (Array.isArray(payload.aud)) { - if (payload.aud.length > 1 && !payload.azp) { - throw new RPError({ - message: 'missing required JWT property azp', - jwt, - }); + /** + * 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 = {}; } - - if (!payload.aud.includes(this.client_id)) { - throw new RPError({ - printf: ['aud is missing the client_id, expected %s to be included in %j', this.client_id, payload.aud], - jwt, - }); + const { span, updatedOptions } = createSpan("ContainerClient-getProperties", options); + try { + return await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), convertTracingToRequestOptionsBase(updatedOptions))); } - } else if (payload.aud !== this.client_id) { - throw new RPError({ - printf: ['aud mismatch, expected %s, got: %s', this.client_id, payload.aud], - jwt, - }); - } - } - - if (payload.azp !== undefined) { - let { additionalAuthorizedParties } = instance(this).get('options') || {}; - - if (typeof additionalAuthorizedParties === 'string') { - additionalAuthorizedParties = [this.client_id, additionalAuthorizedParties]; - } else if (Array.isArray(additionalAuthorizedParties)) { - additionalAuthorizedParties = [this.client_id, ...additionalAuthorizedParties]; - } else { - additionalAuthorizedParties = [this.client_id]; - } - - if (!additionalAuthorizedParties.includes(payload.azp)) { - throw new RPError({ - printf: ['azp mismatch, got: %s', payload.azp], - jwt, - }); - } - } - - let key; - - if (isSelfIssued) { - try { - assert(isPlainObject(payload.sub_jwk)); - key = jose.JWK.asKey(payload.sub_jwk); - assert.equal(key.type, 'public'); - } catch (err) { - throw new RPError({ - message: 'failed to use sub_jwk claim as an asymmetric JSON Web Key', - jwt, - }); - } - if (key.thumbprint !== payload.sub) { - throw new RPError({ - message: 'failed to match the subject with sub_jwk', - jwt, - }); - } - } else if (header.alg.startsWith('HS')) { - key = await this.joseSecret(); - } else if (header.alg !== 'none') { - key = await this.issuer.queryKeyStore(header); - } - - if (!key && header.alg === 'none') { - return { protected: header, payload }; - } - - try { - return { - ...jose.JWS.verify(jwt, key, { complete: true }), - payload, - }; - } catch (err) { - throw new RPError({ - message: 'failed to validate JWT signature', - jwt, - }); - } - } - - /** - * @name refresh - * @api public - */ - async refresh(refreshToken, { exchangeBody, clientAssertionPayload, DPoP } = {}) { - let token = refreshToken; - - if (token instanceof TokenSet) { - if (!token.refresh_token) { - throw new TypeError('refresh_token not present in TokenSet'); - } - token = token.refresh_token; - } - - const tokenset = await this.grant({ - ...exchangeBody, - grant_type: 'refresh_token', - refresh_token: String(token), - }, { clientAssertionPayload, DPoP }); - - if (tokenset.id_token) { - await this.decryptIdToken(tokenset); - await this.validateIdToken(tokenset, null, 'token', null); - - if (refreshToken instanceof TokenSet && refreshToken.id_token) { - const expectedSub = refreshToken.claims().sub; - const actualSub = tokenset.claims().sub; - if (actualSub !== expectedSub) { - throw new RPError({ - printf: ['sub mismatch, expected %s, got: %s', expectedSub, actualSub], - jwt: tokenset.id_token, - }); + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); } - } - } - - return tokenset; - } - - async requestResource( - resourceUrl, - accessToken, - { - method, - headers, - body, - DPoP, - // eslint-disable-next-line no-nested-ternary - tokenType = DPoP ? 'DPoP' : accessToken instanceof TokenSet ? accessToken.token_type : 'Bearer', - } = {}, - ) { - if (accessToken instanceof TokenSet) { - if (!accessToken.access_token) { - throw new TypeError('access_token not present in TokenSet'); - } - accessToken = accessToken.access_token; // eslint-disable-line no-param-reassign - } - - const requestOpts = { - headers: { - Authorization: authorizationHeaderValue(accessToken, tokenType), - ...headers, - }, - body, - }; - - const mTLS = !!this.tls_client_certificate_bound_access_tokens; - - return request.call(this, { - ...requestOpts, - responseType: 'buffer', - method, - url: resourceUrl, - }, { accessToken, mTLS, DPoP }); - } - - /** - * @name userinfo - * @api public - */ - async userinfo(accessToken, { - method = 'GET', via = 'header', tokenType, params, DPoP, - } = {}) { - assertIssuerConfiguration(this.issuer, 'userinfo_endpoint'); - const options = { - tokenType, - method: String(method).toUpperCase(), - DPoP, - }; - - if (options.method !== 'GET' && options.method !== 'POST') { - throw new TypeError('#userinfo() method can only be POST or a GET'); - } - - if (via === 'query' && options.method !== 'GET') { - throw new TypeError('userinfo endpoints will only parse query strings for GET requests'); - } else if (via === 'body' && options.method !== 'POST') { - throw new TypeError('can only send body on POST'); - } - - const jwt = !!(this.userinfo_signed_response_alg || this.userinfo_encrypted_response_alg); - - if (jwt) { - options.headers = { Accept: 'application/jwt' }; - } else { - options.headers = { Accept: 'application/json' }; - } - - const mTLS = !!this.tls_client_certificate_bound_access_tokens; - - let targetUrl; - if (mTLS && this.issuer.mtls_endpoint_aliases) { - targetUrl = this.issuer.mtls_endpoint_aliases.userinfo_endpoint; - } - - targetUrl = new url.URL(targetUrl || this.issuer.userinfo_endpoint); - - // when via is not header we clear the Authorization header and add either - // query string parameters or urlencoded body access_token parameter - if (via === 'query') { - options.headers.Authorization = undefined; - targetUrl.searchParams.append('access_token', accessToken instanceof TokenSet ? accessToken.access_token : accessToken); - } else if (via === 'body') { - options.headers.Authorization = undefined; - options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; - options.body = new url.URLSearchParams(); - options.body.append('access_token', accessToken instanceof TokenSet ? accessToken.access_token : accessToken); - } - - // handle additional parameters, GET via querystring, POST via urlencoded body - if (params) { - if (options.method === 'GET') { - Object.entries(params).forEach(([key, value]) => { - targetUrl.searchParams.append(key, value); - }); - } else if (options.body) { // POST && via body - Object.entries(params).forEach(([key, value]) => { - options.body.append(key, value); - }); - } else { // POST && via header - options.body = new url.URLSearchParams(); - options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; - Object.entries(params).forEach(([key, value]) => { - options.body.append(key, value); - }); - } - } - - if (options.body) { - options.body = options.body.toString(); } - - const response = await this.requestResource(targetUrl, accessToken, options); - - let parsed = processResponse(response, { bearer: true }); - - if (jwt) { - if (!JWT_CONTENT.test(response.headers['content-type'])) { - throw new RPError({ - message: 'expected application/jwt response from the userinfo_endpoint', - response, - }); - } - - const body = response.body.toString(); - const userinfo = await this.decryptJWTUserinfo(body); - if (!this.userinfo_signed_response_alg) { + /** + * 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 = {}; + } + const { span, updatedOptions } = createSpan("ContainerClient-delete", options); try { - parsed = JSON.parse(userinfo); - assert(isPlainObject(parsed)); - } catch (err) { - throw new RPError({ - message: 'failed to parse userinfo JWE payload as JSON', - jwt: userinfo, - }); + return await this.containerContext.delete(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); } - } else { - ({ payload: parsed } = await this.validateJWTUserinfo(userinfo)); - } - } else { - try { - parsed = JSON.parse(response.body); - } catch (error) { - throw new ParseError(error, response); - } - } - - if (accessToken instanceof TokenSet && accessToken.id_token) { - const expectedSub = accessToken.claims().sub; - if (parsed.sub !== expectedSub) { - throw new RPError({ - printf: ['userinfo sub mismatch, expected %s, got: %s', expectedSub, parsed.sub], - body: parsed, - jwt: accessToken.id_token, - }); - } - } - - return parsed; - } - - /** - * @name derivedKey - * @api private - */ - async derivedKey(len) { - const cacheKey = `${len}_key`; - if (instance(this).has(cacheKey)) { - return instance(this).get(cacheKey); - } - - const hash = len <= 256 ? 'sha256' : len <= 384 ? 'sha384' : len <= 512 ? 'sha512' : false; // eslint-disable-line no-nested-ternary - if (!hash) { - throw new Error('unsupported symmetric encryption key derivation'); - } - - const derivedBuffer = crypto.createHash(hash) - .update(this.client_secret) - .digest() - .slice(0, len / 8); - - const key = jose.JWK.asKey({ k: base64url.encode(derivedBuffer), kty: 'oct' }); - instance(this).set(cacheKey, key); - - return key; - } - - /** - * @name joseSecret - * @api private - */ - async joseSecret(alg) { - if (!this.client_secret) { - throw new TypeError('client_secret is required'); - } - if (/^A(\d{3})(?:GCM)?KW$/.test(alg)) { - return this.derivedKey(parseInt(RegExp.$1, 10)); - } - - if (/^A(\d{3})(?:GCM|CBC-HS(\d{3}))$/.test(alg)) { - return this.derivedKey(parseInt(RegExp.$2 || RegExp.$1, 10)); - } - - if (instance(this).has('jose_secret')) { - return instance(this).get('jose_secret'); - } - - const key = jose.JWK.asKey({ k: base64url.encode(this.client_secret), kty: 'oct' }); - instance(this).set('jose_secret', key); - - return key; - } - - /** - * @name grant - * @api public - */ - async grant(body, { clientAssertionPayload, DPoP } = {}) { - assertIssuerConfiguration(this.issuer, 'token_endpoint'); - const response = await authenticatedPost.call( - this, - 'token', - { - form: body, - responseType: 'json', - }, - { clientAssertionPayload, DPoP }, - ); - const responseBody = processResponse(response); - - return new TokenSet(responseBody); - } - - /** - * @name deviceAuthorization - * @api public - */ - async deviceAuthorization(params = {}, { exchangeBody, clientAssertionPayload, DPoP } = {}) { - assertIssuerConfiguration(this.issuer, 'device_authorization_endpoint'); - assertIssuerConfiguration(this.issuer, 'token_endpoint'); - - const body = authorizationParams.call(this, { - client_id: this.client_id, - redirect_uri: null, - response_type: null, - ...params, - }); - - const response = await authenticatedPost.call( - this, - 'device_authorization', - { - responseType: 'json', - form: body, - }, - { clientAssertionPayload, endpointAuthMethod: 'token' }, - ); - const responseBody = processResponse(response); - - return new DeviceFlowHandle({ - client: this, - exchangeBody, - clientAssertionPayload, - response: responseBody, - maxAge: params.max_age, - DPoP, - }); - } - - /** - * @name revoke - * @api public - */ - async revoke(token, hint, { revokeBody, clientAssertionPayload } = {}) { - assertIssuerConfiguration(this.issuer, 'revocation_endpoint'); - if (hint !== undefined && typeof hint !== 'string') { - throw new TypeError('hint must be a string'); - } - - const form = { ...revokeBody, token }; - - if (hint) { - form.token_type_hint = hint; - } - - const response = await authenticatedPost.call( - this, - 'revocation', { - form, - }, { clientAssertionPayload }, - ); - processResponse(response, { body: false }); - } - - /** - * @name introspect - * @api public - */ - async introspect(token, hint, { introspectBody, clientAssertionPayload } = {}) { - assertIssuerConfiguration(this.issuer, 'introspection_endpoint'); - if (hint !== undefined && typeof hint !== 'string') { - throw new TypeError('hint must be a string'); - } - - const form = { ...introspectBody, token }; - if (hint) { - form.token_type_hint = hint; - } - - const response = await authenticatedPost.call( - this, - 'introspection', - { form, responseType: 'json' }, - { clientAssertionPayload }, - ); - - const responseBody = processResponse(response); - - return responseBody; - } - - /** - * @name fetchDistributedClaims - * @api public - */ - async fetchDistributedClaims(claims, tokens = {}) { - if (!isPlainObject(claims)) { - throw new TypeError('claims argument must be a plain object'); - } - - if (!isPlainObject(claims._claim_sources)) { - return claims; - } - - if (!isPlainObject(claims._claim_names)) { - return claims; - } - - const distributedSources = Object.entries(claims._claim_sources) - .filter(([, value]) => value && value.endpoint); - - await Promise.all(distributedSources.map(async ([sourceName, def]) => { - try { - const requestOpts = { - headers: { - Accept: 'application/jwt', - Authorization: authorizationHeaderValue(def.access_token || tokens[sourceName]), - }, - }; - - const response = await request.call(this, { - ...requestOpts, - method: 'GET', - url: def.endpoint, - }); - const body = processResponse(response, { bearer: true }); - - const decoded = await claimJWT.call(this, 'distributed', body); - delete claims._claim_sources[sourceName]; - Object.entries(claims._claim_names).forEach( - assignClaim(claims, decoded, sourceName, false), - ); - } catch (err) { - err.src = sourceName; - throw err; - } - })); - - cleanUpClaims(claims); - return claims; - } - - /** - * @name unpackAggregatedClaims - * @api public - */ - async unpackAggregatedClaims(claims) { - if (!isPlainObject(claims)) { - throw new TypeError('claims argument must be a plain object'); - } - - if (!isPlainObject(claims._claim_sources)) { - return claims; - } - - if (!isPlainObject(claims._claim_names)) { - return claims; - } - - const aggregatedSources = Object.entries(claims._claim_sources) - .filter(([, value]) => value && value.JWT); - - await Promise.all(aggregatedSources.map(async ([sourceName, def]) => { - try { - const decoded = await claimJWT.call(this, 'aggregated', def.JWT); - delete claims._claim_sources[sourceName]; - Object.entries(claims._claim_names).forEach(assignClaim(claims, decoded, sourceName)); - } catch (err) { - err.src = sourceName; - throw err; - } - })); - - cleanUpClaims(claims); - return claims; - } - - /** - * @name register - * @api public - */ - static async register(metadata, options = {}) { - const { initialAccessToken, jwks, ...clientOptions } = options; - - assertIssuerConfiguration(this.issuer, 'registration_endpoint'); - - if (jwks !== undefined && !(metadata.jwks || metadata.jwks_uri)) { - const keystore = getKeystore.call(this, jwks); - metadata.jwks = keystore.toJWKS(false); - // eslint-disable-next-line no-restricted-syntax - for (const jwk of metadata.jwks.keys) { - if (jwk.kid.startsWith('DONOTUSE.')) { - delete jwk.kid; + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); } - } - } - - const response = await request.call(this, { - headers: initialAccessToken ? { - Authorization: authorizationHeaderValue(initialAccessToken), - } : undefined, - responseType: 'json', - json: metadata, - url: this.issuer.registration_endpoint, - method: 'POST', - }); - const responseBody = processResponse(response, { statusCode: 201, bearer: true }); - - return new this(responseBody, jwks, clientOptions); - } - - /** - * @name metadata - * @api public - */ - get metadata() { - const copy = {}; - instance(this).get('metadata').forEach((value, key) => { - copy[key] = value; - }); - return copy; - } - - /** - * @name fromUri - * @api public - */ - static async fromUri(registrationClientUri, registrationAccessToken, jwks, clientOptions) { - const response = await request.call(this, { - method: 'GET', - url: registrationClientUri, - responseType: 'json', - headers: { Authorization: authorizationHeaderValue(registrationAccessToken) }, - }); - const responseBody = processResponse(response, { bearer: true }); - - return new this(responseBody, jwks, clientOptions); - } - - /** - * @name requestObject - * @api public - */ - async requestObject(requestObject = {}, { - sign: signingAlgorithm = this.request_object_signing_alg || 'none', - encrypt: { - alg: eKeyManagement = this.request_object_encryption_alg, - enc: eContentEncryption = this.request_object_encryption_enc || 'A128CBC-HS256', - } = {}, - } = {}) { - if (!isPlainObject(requestObject)) { - throw new TypeError('requestObject must be a plain object'); } - - let signed; - let key; - - const fapi = this.constructor.name === 'FAPIClient'; - const unix = now(); - const header = { alg: signingAlgorithm, typ: 'oauth-authz-req+jwt' }; - const payload = JSON.stringify(defaults({}, requestObject, { - iss: this.client_id, - aud: this.issuer.issuer, - client_id: this.client_id, - jti: random(), - iat: unix, - exp: unix + 300, - ...(fapi ? { nbf: unix } : undefined), - })); - - if (signingAlgorithm === 'none') { - signed = [ - base64url.encode(JSON.stringify(header)), - base64url.encode(payload), - '', - ].join('.'); - } else { - const symmetric = signingAlgorithm.startsWith('HS'); - if (symmetric) { - key = await this.joseSecret(); - } else { - const keystore = instance(this).get('keystore'); - - if (!keystore) { - throw new TypeError(`no keystore present for client, cannot sign using alg ${signingAlgorithm}`); + /** + * 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 = {}) { + var _a, _b; + const { span, updatedOptions } = createSpan("ContainerClient-deleteIfExists", options); + try { + const res = await this.delete(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } - key = keystore.get({ alg: signingAlgorithm, use: 'sig' }); - if (!key) { - throw new TypeError(`no key to sign with found for alg ${signingAlgorithm}`); + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when deleting a container only if it exists.", + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); } - } - - signed = jose.JWS.sign(payload, key, { - ...header, - kid: symmetric || key.kid.startsWith('DONOTUSE.') ? undefined : key.kid, - }); - } - - if (!eKeyManagement) { - return signed; - } - - const fields = { alg: eKeyManagement, enc: eContentEncryption, cty: 'oauth-authz-req+jwt' }; - - if (fields.alg.match(/^(RSA|ECDH)/)) { - [key] = await this.issuer.queryKeyStore({ - alg: fields.alg, - enc: fields.enc, - use: 'enc', - }, { allowMulti: true }); - } else { - key = await this.joseSecret(fields.alg === 'dir' ? fields.enc : fields.alg); - } - - return jose.JWE.encrypt(signed, key, { - ...fields, - kid: key.kty === 'oct' ? undefined : key.kid, - }); - } - - /** - * @name pushedAuthorizationRequest - * @api public - */ - async pushedAuthorizationRequest(params = {}, { clientAssertionPayload } = {}) { - assertIssuerConfiguration(this.issuer, 'pushed_authorization_request_endpoint'); - - const body = { - ...('request' in params ? params : authorizationParams.call(this, params)), - client_id: this.client_id, - }; - - const response = await authenticatedPost.call( - this, - 'pushed_authorization_request', - { - responseType: 'json', - form: body, - }, - { clientAssertionPayload, endpointAuthMethod: 'token' }, - ); - const responseBody = processResponse(response, { statusCode: 201 }); - - if (!('expires_in' in responseBody)) { - throw new RPError({ - message: 'expected expires_in in Pushed Authorization Successful Response', - response, - }); - } - if (typeof responseBody.expires_in !== 'number') { - throw new RPError({ - message: 'invalid expires_in value in Pushed Authorization Successful Response', - response, - }); - } - if (!('request_uri' in responseBody)) { - throw new RPError({ - message: 'expected request_uri in Pushed Authorization Successful Response', - response, - }); - } - if (typeof responseBody.request_uri !== 'string') { - throw new RPError({ - message: 'invalid request_uri value in Pushed Authorization Successful Response', - response, - }); - } - - return responseBody; - } - - /** - * @name issuer - * @api public - */ - static get issuer() { - return issuer; - } - - /** - * @name issuer - * @api public - */ - get issuer() { // eslint-disable-line class-methods-use-this - return issuer; - } - - /* istanbul ignore next */ - [inspect.custom]() { - return `${this.constructor.name} ${inspect(this.metadata, { - depth: Infinity, - colors: process.stdout.isTTY, - compact: false, - sorted: true, - })}`; - } -}; - -/** - * @name validateJARM - * @api private - */ -async function validateJARM(response) { - const expectedAlg = this.authorization_signed_response_alg; - const { payload } = await this.validateJWT(response, expectedAlg, ['iss', 'exp', 'aud']); - return pickCb(payload); -} - -Object.defineProperty(BaseClient.prototype, 'validateJARM', { - enumerable: true, - configurable: true, - value(...args) { - process.emitWarning( - "The JARM API implements an OIDF implementer's draft. Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.", - 'DraftWarning', - ); - Object.defineProperty(BaseClient.prototype, 'validateJARM', { - enumerable: true, - configurable: true, - value: validateJARM, - }); - return this.validateJARM(...args); - }, -}); - -/** - * @name dpopProof - * @api private - */ -function dpopProof(payload, jwk, accessToken) { - if (!isPlainObject(payload)) { - throw new TypeError('payload must be a plain object'); - } - - let key; - try { - key = jose.JWK.asKey(jwk); - assert(key.type === 'private'); - } catch (err) { - throw new TypeError('"DPoP" option must be an asymmetric private key to sign the DPoP Proof JWT with'); - } - - let { alg } = key; - - if (!alg && this.issuer.dpop_signing_alg_values_supported) { - const algs = key.algorithms('sign'); - alg = this.issuer.dpop_signing_alg_values_supported.find((a) => algs.has(a)); - } - - if (!alg) { - [alg] = key.algorithms('sign'); - } - - return jose.JWS.sign({ - iat: now(), - jti: random(), - ath: accessToken ? base64url.encode(crypto.createHash('sha256').update(accessToken).digest()) : undefined, - ...payload, - }, jwk, { - alg, - typ: 'dpop+jwt', - jwk: pick(key, 'kty', 'crv', 'x', 'y', 'e', 'n'), - }); -} - -Object.defineProperty(BaseClient.prototype, 'dpopProof', { - enumerable: true, - configurable: true, - value(...args) { - process.emitWarning( - 'The DPoP APIs implements an IETF draft (https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-03.html). Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.', - 'DraftWarning', - ); - Object.defineProperty(BaseClient.prototype, 'dpopProof', { - enumerable: true, - configurable: true, - value: dpopProof, - }); - return this.dpopProof(...args); - }, -}); - -module.exports.BaseClient = BaseClient; - - -/***/ }), - -/***/ 23979: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable camelcase */ -const { inspect } = __nccwpck_require__(73837); - -const { RPError, OPError } = __nccwpck_require__(45061); -const instance = __nccwpck_require__(27702); -const now = __nccwpck_require__(8542); -const { authenticatedPost } = __nccwpck_require__(7619); -const processResponse = __nccwpck_require__(28576); -const TokenSet = __nccwpck_require__(39029); - -class DeviceFlowHandle { - constructor({ - client, exchangeBody, clientAssertionPayload, response, maxAge, DPoP, - }) { - ['verification_uri', 'user_code', 'device_code'].forEach((prop) => { - if (typeof response[prop] !== 'string' || !response[prop]) { - throw new RPError(`expected ${prop} string to be returned by Device Authorization Response, got %j`, response[prop]); - } - }); - - if (!Number.isSafeInteger(response.expires_in)) { - throw new RPError('expected expires_in number to be returned by Device Authorization Response, got %j', response.expires_in); - } - - instance(this).expires_at = now() + response.expires_in; - instance(this).client = client; - instance(this).DPoP = DPoP; - instance(this).maxAge = maxAge; - instance(this).exchangeBody = exchangeBody; - instance(this).clientAssertionPayload = clientAssertionPayload; - instance(this).response = response; - instance(this).interval = response.interval * 1000 || 5000; - } - - abort() { - instance(this).aborted = true; - } - - async poll({ signal } = {}) { - if ((signal && signal.aborted) || instance(this).aborted) { - throw new RPError('polling aborted'); - } - - if (this.expired()) { - throw new RPError('the device code %j has expired and the device authorization session has concluded', this.device_code); - } - - await new Promise((resolve) => setTimeout(resolve, instance(this).interval)); - - const response = await authenticatedPost.call( - instance(this).client, - 'token', - { - form: { - ...instance(this).exchangeBody, - grant_type: 'urn:ietf:params:oauth:grant-type:device_code', - device_code: this.device_code, - }, - responseType: 'json', - }, - { clientAssertionPayload: instance(this).clientAssertionPayload, DPoP: instance(this).DPoP }, - ); - - let responseBody; - try { - responseBody = processResponse(response); - } catch (err) { - switch (err instanceof OPError && err.error) { - case 'slow_down': - instance(this).interval += 5000; - case 'authorization_pending': // eslint-disable-line no-fallthrough - return this.poll({ signal }); - default: - throw err; - } - } - - const tokenset = new TokenSet(responseBody); - - if ('id_token' in tokenset) { - await instance(this).client.decryptIdToken(tokenset); - await instance(this).client.validateIdToken(tokenset, undefined, 'token', instance(this).maxAge); - } - - return tokenset; - } - - get device_code() { - return instance(this).response.device_code; - } - - get user_code() { - return instance(this).response.user_code; - } - - get verification_uri() { - return instance(this).response.verification_uri; - } - - get verification_uri_complete() { - return instance(this).response.verification_uri_complete; - } - - get expires_in() { - return Math.max.apply(null, [instance(this).expires_at - now(), 0]); - } - - expired() { - return this.expires_in === 0; - } - - /* istanbul ignore next */ - [inspect.custom]() { - return `${this.constructor.name} ${inspect(instance(this).response, { - depth: Infinity, - colors: process.stdout.isTTY, - compact: false, - sorted: true, - })}`; - } -} - -module.exports = DeviceFlowHandle; - - -/***/ }), - -/***/ 45061: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable camelcase */ -const { format } = __nccwpck_require__(73837); - -const makeError = __nccwpck_require__(21381); - -function OPError({ - error_description, - error, - error_uri, - session_state, - state, - scope, -}, response) { - OPError.super.call(this, !error_description ? error : `${error} (${error_description})`); - - Object.assign( - this, - { error }, - (error_description && { error_description }), - (error_uri && { error_uri }), - (state && { state }), - (scope && { scope }), - (session_state && { session_state }), - ); - - if (response) { - Object.defineProperty(this, 'response', { - value: response, - }); - } -} - -makeError(OPError); - -function RPError(...args) { - if (typeof args[0] === 'string') { - RPError.super.call(this, format(...args)); - } else { - const { - message, printf, response, ...rest - } = args[0]; - if (printf) { - RPError.super.call(this, format(...printf)); - } else { - RPError.super.call(this, message); - } - Object.assign(this, rest); - if (response) { - Object.defineProperty(this, 'response', { - value: response, - }); - } - } -} - -makeError(RPError); - -module.exports = { - OPError, - RPError, -}; - - -/***/ }), - -/***/ 63217: -/***/ ((module) => { - -function assertSigningAlgValuesSupport(endpoint, issuer, properties) { - if (!issuer[`${endpoint}_endpoint`]) return; - - const eam = `${endpoint}_endpoint_auth_method`; - const easa = `${endpoint}_endpoint_auth_signing_alg`; - const easavs = `${endpoint}_endpoint_auth_signing_alg_values_supported`; - - if (properties[eam] && properties[eam].endsWith('_jwt') && !properties[easa] && !issuer[easavs]) { - throw new TypeError(`${easavs} must be configured on the issuer if ${easa} is not defined on a client`); - } -} - -function assertIssuerConfiguration(issuer, endpoint) { - if (!issuer[endpoint]) { - throw new TypeError(`${endpoint} must be configured on the issuer`); - } -} - -module.exports = { - assertSigningAlgValuesSupport, - assertIssuerConfiguration, -}; - - -/***/ }), - -/***/ 61827: -/***/ ((module) => { - -let encode; -if (Buffer.isEncoding('base64url')) { - encode = (input, encoding = 'utf8') => Buffer.from(input, encoding).toString('base64url'); -} else { - const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); - encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64')); -} - -const decode = (input) => Buffer.from(input, 'base64'); - -module.exports.decode = decode; -module.exports.encode = encode; - - -/***/ }), - -/***/ 7619: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const jose = __nccwpck_require__(16425); - -const { assertIssuerConfiguration } = __nccwpck_require__(63217); -const { random } = __nccwpck_require__(75421); -const now = __nccwpck_require__(8542); -const request = __nccwpck_require__(92946); -const instance = __nccwpck_require__(27702); -const merge = __nccwpck_require__(2494); - -const formUrlEncode = (value) => encodeURIComponent(value).replace(/%20/g, '+'); - -async function clientAssertion(endpoint, payload) { - let alg = this[`${endpoint}_endpoint_auth_signing_alg`]; - if (!alg) { - assertIssuerConfiguration(this.issuer, `${endpoint}_endpoint_auth_signing_alg_values_supported`); - } - - if (this[`${endpoint}_endpoint_auth_method`] === 'client_secret_jwt') { - const key = await this.joseSecret(); - - if (!alg) { - const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`]; - alg = Array.isArray(supported) && supported.find((signAlg) => key.algorithms('sign').has(signAlg)); - } - - return jose.JWS.sign(payload, key, { alg, typ: 'JWT' }); - } - - const keystore = instance(this).get('keystore'); - - if (!keystore) { - throw new TypeError('no client jwks provided for signing a client assertion with'); - } - - if (!alg) { - const algs = new Set(); - - keystore.all().forEach((key) => { - key.algorithms('sign').forEach(Set.prototype.add.bind(algs)); - }); - - const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`]; - alg = Array.isArray(supported) && supported.find((signAlg) => algs.has(signAlg)); - } - - const key = keystore.get({ alg, use: 'sig' }); - if (!key) { - throw new TypeError(`no key found in client jwks to sign a client assertion with using alg ${alg}`); - } - return jose.JWS.sign(payload, key, { alg, typ: 'JWT', kid: key.kid.startsWith('DONOTUSE.') ? undefined : key.kid }); -} - -async function authFor(endpoint, { clientAssertionPayload } = {}) { - const authMethod = this[`${endpoint}_endpoint_auth_method`]; - switch (authMethod) { - case 'self_signed_tls_client_auth': - case 'tls_client_auth': - case 'none': - return { form: { client_id: this.client_id } }; - case 'client_secret_post': - if (!this.client_secret) { - throw new TypeError('client_secret_post client authentication method requires a client_secret'); - } - return { form: { client_id: this.client_id, client_secret: this.client_secret } }; - case 'private_key_jwt': - case 'client_secret_jwt': { - const timestamp = now(); - - const mTLS = endpoint === 'token' && this.tls_client_certificate_bound_access_tokens; - const audience = [...new Set([ - this.issuer.issuer, - this.issuer.token_endpoint, - this.issuer[`${endpoint}_endpoint`], - mTLS && this.issuer.mtls_endpoint_aliases - ? this.issuer.mtls_endpoint_aliases.token_endpoint : undefined, - ].filter(Boolean))]; - - const assertion = await clientAssertion.call(this, endpoint, { - iat: timestamp, - exp: timestamp + 60, - jti: random(), - iss: this.client_id, - sub: this.client_id, - aud: audience, - ...clientAssertionPayload, - }); - - return { - form: { - client_id: this.client_id, - client_assertion: assertion, - client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', - }, - }; - } - default: { // client_secret_basic - // This is correct behaviour, see https://tools.ietf.org/html/rfc6749#section-2.3.1 and the - // related appendix. (also https://github.com/panva/node-openid-client/pull/91) - // > The client identifier is encoded using the - // > "application/x-www-form-urlencoded" encoding algorithm per - // > Appendix B, and the encoded value is used as the username; the client - // > password is encoded using the same algorithm and used as the - // > password. - if (!this.client_secret) { - throw new TypeError('client_secret_basic client authentication method requires a client_secret'); - } - const encoded = `${formUrlEncode(this.client_id)}:${formUrlEncode(this.client_secret)}`; - const value = Buffer.from(encoded).toString('base64'); - return { headers: { Authorization: `Basic ${value}` } }; - } - } -} - -function resolveResponseType() { - const { length, 0: value } = this.response_types; - - if (length === 1) { - return value; - } - - return undefined; -} - -function resolveRedirectUri() { - const { length, 0: value } = this.redirect_uris || []; - - if (length === 1) { - return value; - } - - return undefined; -} - -async function authenticatedPost(endpoint, opts, { - clientAssertionPayload, endpointAuthMethod = endpoint, DPoP, -} = {}) { - const auth = await authFor.call(this, endpointAuthMethod, { clientAssertionPayload }); - const requestOpts = merge(opts, auth); - - const mTLS = this[`${endpointAuthMethod}_endpoint_auth_method`].includes('tls_client_auth') - || (endpoint === 'token' && this.tls_client_certificate_bound_access_tokens); - - let targetUrl; - if (mTLS && this.issuer.mtls_endpoint_aliases) { - targetUrl = this.issuer.mtls_endpoint_aliases[`${endpoint}_endpoint`]; - } - - targetUrl = targetUrl || this.issuer[`${endpoint}_endpoint`]; - - if ('form' in requestOpts) { - for (const [key, value] of Object.entries(requestOpts.form)) { // eslint-disable-line no-restricted-syntax, max-len - if (typeof value === 'undefined') { - delete requestOpts.form[key]; - } - } - } - - return request.call(this, { - ...requestOpts, - method: 'POST', - url: targetUrl, - }, { mTLS, DPoP }); -} - -module.exports = { - resolveResponseType, - resolveRedirectUri, - authFor, - authenticatedPost, -}; - - -/***/ }), - -/***/ 27556: -/***/ ((module) => { - -const OIDC_DISCOVERY = '/.well-known/openid-configuration'; -const OAUTH2_DISCOVERY = '/.well-known/oauth-authorization-server'; -const WEBFINGER = '/.well-known/webfinger'; -const REL = 'http://openid.net/specs/connect/1.0/issuer'; -const AAD_MULTITENANT_DISCOVERY = [ - `https://login.microsoftonline.com/common${OIDC_DISCOVERY}`, - `https://login.microsoftonline.com/common/v2.0${OIDC_DISCOVERY}`, - `https://login.microsoftonline.com/organizations/v2.0${OIDC_DISCOVERY}`, - `https://login.microsoftonline.com/consumers/v2.0${OIDC_DISCOVERY}`, -]; - -const CLIENT_DEFAULTS = { - grant_types: ['authorization_code'], - id_token_signed_response_alg: 'RS256', - authorization_signed_response_alg: 'RS256', - response_types: ['code'], - token_endpoint_auth_method: 'client_secret_basic', -}; - -const ISSUER_DEFAULTS = { - claim_types_supported: ['normal'], - claims_parameter_supported: false, - grant_types_supported: ['authorization_code', 'implicit'], - request_parameter_supported: false, - request_uri_parameter_supported: true, - require_request_uri_registration: false, - response_modes_supported: ['query', 'fragment'], - token_endpoint_auth_methods_supported: ['client_secret_basic'], -}; - -const CALLBACK_PROPERTIES = [ - 'access_token', // 6749 - 'code', // 6749 - 'error', // 6749 - 'error_description', // 6749 - 'error_uri', // 6749 - 'expires_in', // 6749 - 'id_token', // Core 1.0 - 'state', // 6749 - 'token_type', // 6749 - 'session_state', // Session Management - 'response', // JARM -]; - -const JWT_CONTENT = /^application\/jwt/; - -const HTTP_OPTIONS = Symbol('openid-client.custom.http-options'); -const CLOCK_TOLERANCE = Symbol('openid-client.custom.clock-tolerance'); - -module.exports = { - AAD_MULTITENANT_DISCOVERY, - CALLBACK_PROPERTIES, - CLIENT_DEFAULTS, - CLOCK_TOLERANCE, - HTTP_OPTIONS, - ISSUER_DEFAULTS, - JWT_CONTENT, - OAUTH2_DISCOVERY, - OIDC_DISCOVERY, - REL, - WEBFINGER, -}; - - -/***/ }), - -/***/ 21004: -/***/ ((module) => { - -module.exports = (obj) => JSON.parse(JSON.stringify(obj)); - - -/***/ }), - -/***/ 13098: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable no-restricted-syntax, no-continue */ - -const isPlainObject = __nccwpck_require__(39862); - -function defaults(deep, target, ...sources) { - for (const source of sources) { - if (!isPlainObject(source)) { - continue; - } - for (const [key, value] of Object.entries(source)) { - /* istanbul ignore if */ - if (key === '__proto__' || key === 'constructor') { - continue; - } - if (typeof target[key] === 'undefined' && typeof value !== 'undefined') { - target[key] = value; - } - - if (deep && isPlainObject(target[key]) && isPlainObject(value)) { - defaults(true, target[key], value); - } - } - } - - return target; -} - -module.exports = defaults.bind(undefined, false); -module.exports.deep = defaults.bind(undefined, true); - - -/***/ }), - -/***/ 75421: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createHash, randomBytes } = __nccwpck_require__(6113); - -const base64url = __nccwpck_require__(61827); - -const random = (bytes = 32) => base64url.encode(randomBytes(bytes)); - -module.exports = { - random, - state: random, - nonce: random, - codeVerifier: random, - codeChallenge: (codeVerifier) => base64url.encode(createHash('sha256').update(codeVerifier).digest()), -}; - - -/***/ }), - -/***/ 61797: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const url = __nccwpck_require__(57310); -const { strict: assert } = __nccwpck_require__(39491); - -module.exports = (target) => { - try { - const { protocol } = new url.URL(target); - assert(protocol.match(/^(https?:)$/)); - return true; - } catch (err) { - throw new TypeError('only valid absolute URLs can be requested'); - } -}; - - -/***/ }), - -/***/ 39862: -/***/ ((module) => { - -module.exports = (a) => !!a && a.constructor === Object; - - -/***/ }), - -/***/ 2494: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable no-restricted-syntax, no-param-reassign, no-continue */ - -const isPlainObject = __nccwpck_require__(39862); - -function merge(target, ...sources) { - for (const source of sources) { - if (!isPlainObject(source)) { - continue; - } - for (const [key, value] of Object.entries(source)) { - /* istanbul ignore if */ - if (key === '__proto__' || key === 'constructor') { - continue; - } - if (isPlainObject(target[key]) && isPlainObject(value)) { - target[key] = merge(target[key], value); - } else if (typeof value !== 'undefined') { - target[key] = value; - } - } - } - - return target; -} - -module.exports = merge; - - -/***/ }), - -/***/ 78857: -/***/ ((module) => { - -module.exports = function pick(object, ...paths) { - const obj = {}; - for (const path of paths) { // eslint-disable-line no-restricted-syntax - if (object[path]) { - obj[path] = object[path]; - } - } - return obj; -}; - - -/***/ }), - -/***/ 28576: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { STATUS_CODES } = __nccwpck_require__(13685); -const { format } = __nccwpck_require__(73837); - -const { OPError } = __nccwpck_require__(45061); - -const REGEXP = /(\w+)=("[^"]*")/g; -const throwAuthenticateErrors = (response) => { - const params = {}; - try { - while ((REGEXP.exec(response.headers['www-authenticate'])) !== null) { - if (RegExp.$1 && RegExp.$2) { - params[RegExp.$1] = RegExp.$2.slice(1, -1); - } - } - } catch (err) {} - - if (params.error) { - throw new OPError(params, response); - } -}; - -const isStandardBodyError = (response) => { - let result = false; - try { - let jsonbody; - if (typeof response.body !== 'object' || Buffer.isBuffer(response.body)) { - jsonbody = JSON.parse(response.body); - } else { - jsonbody = response.body; - } - result = typeof jsonbody.error === 'string' && jsonbody.error.length; - if (result) response.body = jsonbody; - } catch (err) {} - - return result; -}; - -function processResponse(response, { statusCode = 200, body = true, bearer = false } = {}) { - if (response.statusCode !== statusCode) { - if (bearer) { - throwAuthenticateErrors(response); } - - if (isStandardBodyError(response)) { - throw new OPError(response.body, response); + /** + * 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(metadata, 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"); + } + const { span, updatedOptions } = createSpan("ContainerClient-setMetadata", options); + try { + return await this.containerContext.setMetadata(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - - throw new OPError({ - error: format('expected %i %s, got: %i %s', statusCode, STATUS_CODES[statusCode], response.statusCode, STATUS_CODES[response.statusCode]), - }, response); - } - - if (body && !response.body) { - throw new OPError({ - error: format('expected %i %s with body but no body was returned', statusCode, STATUS_CODES[statusCode]), - }, response); - } - - return response.body; -} - -module.exports = processResponse; - - -/***/ }), - -/***/ 92946: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const Got = __nccwpck_require__(93061); - -const pkg = __nccwpck_require__(82696); - -const { deep: defaultsDeep } = __nccwpck_require__(13098); -const isAbsoluteUrl = __nccwpck_require__(61797); -const { HTTP_OPTIONS } = __nccwpck_require__(27556); - -let DEFAULT_HTTP_OPTIONS; -let got; - -const setDefaults = (options) => { - DEFAULT_HTTP_OPTIONS = defaultsDeep({}, options, DEFAULT_HTTP_OPTIONS); - got = Got.extend(DEFAULT_HTTP_OPTIONS); -}; - -setDefaults({ - followRedirect: false, - headers: { 'User-Agent': `${pkg.name}/${pkg.version} (${pkg.homepage})` }, - retry: 0, - timeout: 3500, - throwHttpErrors: false, -}); - -module.exports = async function request(options, { accessToken, mTLS = false, DPoP } = {}) { - const { url } = options; - isAbsoluteUrl(url); - const optsFn = this[HTTP_OPTIONS]; - let opts = options; - - if (DPoP && 'dpopProof' in this) { - opts.headers = opts.headers || {}; - opts.headers.DPoP = this.dpopProof({ - htu: url, - htm: options.method, - }, DPoP, accessToken); - } - - if (optsFn) { - opts = optsFn.call(this, defaultsDeep({}, opts, DEFAULT_HTTP_OPTIONS)); - } - - if ( - mTLS - && ( - (!opts.key || !opts.cert) - && (!opts.https || !((opts.https.key && opts.https.certificate) || opts.https.pfx)) - ) - ) { - throw new TypeError('mutual-TLS certificate and key not set'); - } - - return got(opts); -}; - -module.exports.setDefaults = setDefaults; - - -/***/ }), - -/***/ 8542: -/***/ ((module) => { - -module.exports = () => Math.floor(Date.now() / 1000); - - -/***/ }), - -/***/ 27702: -/***/ ((module) => { - -const privateProps = new WeakMap(); - -module.exports = (ctx) => { - if (!privateProps.has(ctx)) { - privateProps.set(ctx, new Map([['metadata', new Map()]])); - } - return privateProps.get(ctx); -}; - - -/***/ }), - -/***/ 27416: -/***/ ((module) => { - -// Credit: https://github.com/rohe/pyoidc/blob/master/src/oic/utils/webfinger.py - -// -- Normalization -- -// A string of any other type is interpreted as a URI either the form of scheme -// "://" authority path-abempty [ "?" query ] [ "#" fragment ] or authority -// path-abempty [ "?" query ] [ "#" fragment ] per RFC 3986 [RFC3986] and is -// normalized according to the following rules: -// -// If the user input Identifier does not have an RFC 3986 [RFC3986] scheme -// portion, the string is interpreted as [userinfo "@"] host [":" port] -// path-abempty [ "?" query ] [ "#" fragment ] per RFC 3986 [RFC3986]. -// If the userinfo component is present and all of the path component, query -// component, and port component are empty, the acct scheme is assumed. In this -// case, the normalized URI is formed by prefixing acct: to the string as the -// scheme. Per the 'acct' URI Scheme [I‑D.ietf‑appsawg‑acct‑uri], if there is an -// at-sign character ('@') in the userinfo component, it needs to be -// percent-encoded as described in RFC 3986 [RFC3986]. -// For all other inputs without a scheme portion, the https scheme is assumed, -// and the normalized URI is formed by prefixing https:// to the string as the -// scheme. -// If the resulting URI contains a fragment portion, it MUST be stripped off -// together with the fragment delimiter character "#". -// The WebFinger [I‑D.ietf‑appsawg‑webfinger] Resource in this case is the -// resulting URI, and the WebFinger Host is the authority component. -// -// Note: Since the definition of authority in RFC 3986 [RFC3986] is -// [ userinfo "@" ] host [ ":" port ], it is legal to have a user input -// identifier like userinfo@host:port, e.g., alice@example.com:8080. - -const PORT = /^\d+$/; - -function hasScheme(input) { - if (input.includes('://')) return true; - - const authority = input.replace(/(\/|\?)/g, '#').split('#')[0]; - if (authority.includes(':')) { - const index = authority.indexOf(':'); - const hostOrPort = authority.slice(index + 1); - if (!PORT.test(hostOrPort)) { - return true; + /** + * 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 = {}; + } + const { span, updatedOptions } = createSpan("ContainerClient-getAccessPolicy", options); + try { + const response = await this.containerContext.getAccessPolicy(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + 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 = undefined; + 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; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - } - - return false; -} - -function acctSchemeAssumed(input) { - if (!input.includes('@')) return false; - const parts = input.split('@'); - const host = parts[parts.length - 1]; - return !(host.includes(':') || host.includes('/') || host.includes('?')); -} - -function normalize(input) { - if (typeof input !== 'string') { - throw new TypeError('input must be a string'); - } - - let output; - if (hasScheme(input)) { - output = input; - } else if (acctSchemeAssumed(input)) { - output = `acct:${input}`; - } else { - output = `https://${input}`; - } - - return output.split('#')[0]; -} - -module.exports = normalize; - - -/***/ }), - -/***/ 53140: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const Issuer = __nccwpck_require__(27213); -const { OPError, RPError } = __nccwpck_require__(45061); -const Registry = __nccwpck_require__(30730); -const Strategy = __nccwpck_require__(22134); -const TokenSet = __nccwpck_require__(39029); -const { CLOCK_TOLERANCE, HTTP_OPTIONS } = __nccwpck_require__(27556); -const generators = __nccwpck_require__(75421); -const { setDefaults } = __nccwpck_require__(92946); - -module.exports = { - Issuer, - Registry, - Strategy, - TokenSet, - errors: { - OPError, - RPError, - }, - custom: { - setHttpOptionsDefaults: setDefaults, - http_options: HTTP_OPTIONS, - clock_tolerance: CLOCK_TOLERANCE, - }, - generators, -}; - - -/***/ }), - -/***/ 27213: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable max-classes-per-file */ - -const { inspect } = __nccwpck_require__(73837); -const url = __nccwpck_require__(57310); - -const AggregateError = __nccwpck_require__(61231); -const jose = __nccwpck_require__(16425); -const LRU = __nccwpck_require__(7129); -const objectHash = __nccwpck_require__(24856); - -const { RPError } = __nccwpck_require__(45061); -const getClient = __nccwpck_require__(28300); -const registry = __nccwpck_require__(30730); -const processResponse = __nccwpck_require__(28576); -const webfingerNormalize = __nccwpck_require__(27416); -const instance = __nccwpck_require__(27702); -const request = __nccwpck_require__(92946); -const { assertIssuerConfiguration } = __nccwpck_require__(63217); -const { - ISSUER_DEFAULTS, OIDC_DISCOVERY, OAUTH2_DISCOVERY, WEBFINGER, REL, AAD_MULTITENANT_DISCOVERY, -} = __nccwpck_require__(27556); - -const AAD_MULTITENANT = Symbol('AAD_MULTITENANT'); - -class Issuer { - /** - * @name constructor - * @api public - */ - constructor(meta = {}) { - const aadIssValidation = meta[AAD_MULTITENANT]; - delete meta[AAD_MULTITENANT]; - - ['introspection', 'revocation'].forEach((endpoint) => { - // if intro/revocation endpoint auth specific meta is missing use the token ones if they - // are defined - if ( - meta[`${endpoint}_endpoint`] - && meta[`${endpoint}_endpoint_auth_methods_supported`] === undefined - && meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] === undefined - ) { - if (meta.token_endpoint_auth_methods_supported) { - meta[`${endpoint}_endpoint_auth_methods_supported`] = meta.token_endpoint_auth_methods_supported; + /** + * 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(access, containerAcl, options = {}) { + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("ContainerClient-setAccessPolicy", options); + try { + const acl = []; + for (const identifier of containerAcl || []) { + 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 await this.containerContext.setAccessPolicy(Object.assign({ abortSignal: options.abortSignal, access, containerAcl: acl, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); } - if (meta.token_endpoint_auth_signing_alg_values_supported) { - meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] = meta.token_endpoint_auth_signing_alg_values_supported; + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); } - } - }); - - Object.entries(meta).forEach(([key, value]) => { - instance(this).get('metadata').set(key, value); - if (!this[key]) { - Object.defineProperty(this, key, { - get() { return instance(this).get('metadata').get(key); }, - enumerable: true, - }); - } - }); - - instance(this).set('cache', new LRU({ max: 100 })); - - registry.set(this.issuer, this); - - const Client = getClient(this, aadIssValidation); - - Object.defineProperties(this, { - Client: { value: Client }, - FAPIClient: { value: class FAPIClient extends Client {} }, - }); - } - - /** - * @name keystore - * @api public - */ - async keystore(reload = false) { - assertIssuerConfiguration(this, 'jwks_uri'); - - const keystore = instance(this).get('keystore'); - const cache = instance(this).get('cache'); - - if (reload || !keystore) { - cache.reset(); - const response = await request.call(this, { - method: 'GET', - responseType: 'json', - url: this.jwks_uri, - }); - const jwks = processResponse(response); - - const joseKeyStore = jose.JWKS.asKeyStore(jwks, { ignoreErrors: true }); - cache.set('throttle', true, 60 * 1000); - instance(this).set('keystore', joseKeyStore); - return joseKeyStore; - } - - return keystore; - } - - /** - * @name queryKeyStore - * @api private - */ - async queryKeyStore({ - kid, kty, alg, use, key_ops: ops, - }, { allowMulti = false } = {}) { - const cache = instance(this).get('cache'); - - const def = { - kid, kty, alg, use, key_ops: ops, - }; - - const defHash = objectHash(def, { - algorithm: 'sha256', - ignoreUnknown: true, - unorderedArrays: true, - unorderedSets: true, - }); - - // refresh keystore on every unknown key but also only upto once every minute - const freshJwksUri = cache.get(defHash) || cache.get('throttle'); - - const keystore = await this.keystore(!freshJwksUri); - const keys = keystore.all(def); - - if (keys.length === 0) { - throw new RPError({ - printf: ["no valid key found in issuer's jwks_uri for key parameters %j", def], - jwks: keystore, - }); - } - - if (!allowMulti && keys.length > 1 && !kid) { - throw new RPError({ - printf: ["multiple matching keys found in issuer's jwks_uri for key parameters %j, kid must be provided in this case", def], - jwks: keystore, - }); - } - - cache.set(defHash, true); - - return new jose.JWKS.KeyStore(keys); - } - - /** - * @name metadata - * @api public - */ - get metadata() { - const copy = {}; - instance(this).get('metadata').forEach((value, key) => { - copy[key] = value; - }); - return copy; - } - - /** - * @name webfinger - * @api public - */ - static async webfinger(input) { - const resource = webfingerNormalize(input); - const { host } = url.parse(resource); - const webfingerUrl = `https://${host}${WEBFINGER}`; - - const response = await request.call(this, { - method: 'GET', - url: webfingerUrl, - responseType: 'json', - searchParams: { resource, rel: REL }, - followRedirect: true, - }); - const body = processResponse(response); - - const location = Array.isArray(body.links) && body.links.find((link) => typeof link === 'object' && link.rel === REL && link.href); - - if (!location) { - throw new RPError({ - message: 'no issuer found in webfinger response', - body, - }); - } - - if (typeof location.href !== 'string' || !location.href.startsWith('https://')) { - throw new RPError({ - printf: ['invalid issuer location %s', location.href], - body, - }); } - - const expectedIssuer = location.href; - if (registry.has(expectedIssuer)) { - return registry.get(expectedIssuer); + /** + * 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); } - - const issuer = await this.discover(expectedIssuer); - - if (issuer.issuer !== expectedIssuer) { - registry.delete(issuer.issuer); - throw new RPError('discovered issuer mismatch, expected %s, got: %s', expectedIssuer, issuer.issuer); + /** + * 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, body, contentLength, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-uploadBlockBlob", options); + try { + const blockBlobClient = this.getBlockBlobClient(blobName); + const response = await blockBlobClient.upload(body, contentLength, updatedOptions); + return { + blockBlobClient, + response, + }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - return issuer; - } - - /** - * @name discover - * @api public - */ - static async discover(uri) { - const parsed = url.parse(uri); - - if (parsed.pathname.includes('/.well-known/')) { - const response = await request.call(this, { - method: 'GET', - responseType: 'json', - url: uri, - }); - const body = processResponse(response); - return new Issuer({ - ...ISSUER_DEFAULTS, - ...body, - [AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find( - (discoveryURL) => uri.startsWith(discoveryURL), - ), - }); + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-deleteBlob", options); + try { + let blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); + } + return await blobClient.delete(updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - - const pathnames = []; - if (parsed.pathname.endsWith('/')) { - pathnames.push(`${parsed.pathname}${OIDC_DISCOVERY.substring(1)}`); - } else { - pathnames.push(`${parsed.pathname}${OIDC_DISCOVERY}`); + /** + * 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(marker, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-listBlobFlatSegment", options); + try { + const response = await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); + 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((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name), tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - if (parsed.pathname === '/') { - pathnames.push(`${OAUTH2_DISCOVERY}`); - } else { - pathnames.push(`${OAUTH2_DISCOVERY}${parsed.pathname}`); + /** + * 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(delimiter, marker, options = {}) { + var _a; + const { span, updatedOptions } = createSpan("ContainerClient-listBlobHierarchySegment", options); + try { + const response = await this.containerContext.listBlobHierarchySegment(delimiter, Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); + 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((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name), tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.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; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - - const errors = []; - // eslint-disable-next-line no-restricted-syntax - for (const pathname of pathnames) { - try { - const wellKnownUri = url.format({ ...parsed, pathname }); - // eslint-disable-next-line no-await-in-loop - const response = await request.call(this, { - method: 'GET', - responseType: 'json', - url: wellKnownUri, - }); - const body = processResponse(response); - return new Issuer({ - ...ISSUER_DEFAULTS, - ...body, - [AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find( - (discoveryURL) => wellKnownUri.startsWith(discoveryURL), - ), + /** + * 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, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1() { + let listBlobsFlatSegmentResponse; + if (!!marker || marker === undefined) { + do { + listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker, options)); + marker = listBlobsFlatSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); + } while (marker); + } }); - } catch (err) { - errors.push(err); - } - } - - const err = new AggregateError(errors); - err.message = `Issuer.discover() failed.${err.message.split('\n') - .filter((line) => !line.startsWith(' at')).join('\n')}`; - throw err; - } - - /* istanbul ignore next */ - [inspect.custom]() { - return `${this.constructor.name} ${inspect(this.metadata, { - depth: Infinity, - colors: process.stdout.isTTY, - compact: false, - sorted: true, - })}`; - } -} - -module.exports = Issuer; - - -/***/ }), - -/***/ 30730: -/***/ ((module) => { - -const REGISTRY = new Map(); - -module.exports = REGISTRY; - - -/***/ }), - -/***/ 22134: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable no-underscore-dangle */ - -const url = __nccwpck_require__(57310); -const { format } = __nccwpck_require__(73837); - -const cloneDeep = __nccwpck_require__(21004); -const { RPError, OPError } = __nccwpck_require__(45061); -const { BaseClient } = __nccwpck_require__(28300); -const { random, codeChallenge } = __nccwpck_require__(75421); -const pick = __nccwpck_require__(78857); -const { resolveResponseType, resolveRedirectUri } = __nccwpck_require__(7619); - -function verified(err, user, info = {}) { - if (err) { - this.error(err); - } else if (!user) { - this.fail(info); - } else { - this.success(user, info); - } -} - -/** - * @name constructor - * @api public - */ -function OpenIDConnectStrategy({ - client, - params = {}, - passReqToCallback = false, - sessionKey, - usePKCE = true, - extras = {}, -} = {}, verify) { - if (!(client instanceof BaseClient)) { - throw new TypeError('client must be an instance of openid-client Client'); - } - - if (typeof verify !== 'function') { - throw new TypeError('verify callback must be a function'); - } - - if (!client.issuer || !client.issuer.issuer) { - throw new TypeError('client must have an issuer with an identifier'); - } - - this._client = client; - this._issuer = client.issuer; - this._verify = verify; - this._passReqToCallback = passReqToCallback; - this._usePKCE = usePKCE; - this._key = sessionKey || `oidc:${url.parse(this._issuer.issuer).hostname}`; - this._params = cloneDeep(params); - this._extras = cloneDeep(extras); - - if (!this._params.response_type) this._params.response_type = resolveResponseType.call(client); - if (!this._params.redirect_uri) this._params.redirect_uri = resolveRedirectUri.call(client); - if (!this._params.scope) this._params.scope = 'openid'; - - if (this._usePKCE === true) { - const supportedMethods = Array.isArray(this._issuer.code_challenge_methods_supported) - ? this._issuer.code_challenge_methods_supported : false; - - if (supportedMethods && supportedMethods.includes('S256')) { - this._usePKCE = 'S256'; - } else if (supportedMethods && supportedMethods.includes('plain')) { - this._usePKCE = 'plain'; - } else if (supportedMethods) { - throw new TypeError('neither code_challenge_method supported by the client is supported by the issuer'); - } else { - this._usePKCE = 'S256'; } - } else if (typeof this._usePKCE === 'string' && !['plain', 'S256'].includes(this._usePKCE)) { - throw new TypeError(`${this._usePKCE} is not valid/implemented PKCE code_challenge_method`); - } - - this.name = url.parse(client.issuer.issuer).hostname; -} - -OpenIDConnectStrategy.prototype.authenticate = function authenticate(req, options) { - (async () => { - const client = this._client; - if (!req.session) { - throw new TypeError('authentication requires session support'); + /** + * Returns an AsyncIterableIterator of {@link BlobItem} objects + * + * @param options - Options to list blobs operation. + */ + listItems(options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItems_1() { + var e_1, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const listBlobsFlatSegmentResponse = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_1) throw e_1.error; } + } + }); } - const reqParams = client.callbackParams(req); - const sessionKey = this._key; - - /* start authentication request */ - if (Object.keys(reqParams).length === 0) { - // provide options object with extra authentication parameters - const params = { - state: random(), - ...this._params, - ...options, - }; - - if (!params.nonce && params.response_type.includes('id_token')) { - params.nonce = random(); - } - - req.session[sessionKey] = pick(params, 'nonce', 'state', 'max_age', 'response_type'); - - if (this._usePKCE && params.response_type.includes('code')) { - const verifier = random(); - req.session[sessionKey].code_verifier = verifier; - - switch (this._usePKCE) { // eslint-disable-line default-case - case 'S256': - params.code_challenge = codeChallenge(verifier); - params.code_challenge_method = 'S256'; - break; - case 'plain': - params.code_challenge = verifier; - break; + /** + * 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 include = []; + if (options.includeCopy) { + include.push("copy"); } - } - - this.redirect(client.authorizationUrl(params)); - return; - } - /* end authentication request */ - - /* start authentication response */ - - const session = req.session[sessionKey]; - if (Object.keys(session || {}).length === 0) { - throw new Error(format('did not find expected authorization request details in session, req.session["%s"] is %j', sessionKey, session)); + if (options.includeDeleted) { + include.push("deleted"); + } + if (options.includeMetadata) { + include.push("metadata"); + } + if (options.includeSnapshots) { + include.push("snapshots"); + } + if (options.includeVersions) { + include.push("versions"); + } + if (options.includeUncommitedBlobs) { + include.push("uncommittedblobs"); + } + if (options.includeTags) { + include.push("tags"); + } + if (options.includeDeletedWithVersions) { + include.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include.push("legalhold"); + } + if (options.prefix === "") { + options.prefix = undefined; + } + const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); + // AsyncIterableIterator to iterate over blobs + 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)); + }, + }; } - - const { - state, nonce, max_age: maxAge, code_verifier: codeVerifier, response_type: responseType, - } = session; - - try { - delete req.session[sessionKey]; - } catch (err) {} - - const opts = { - redirect_uri: this._params.redirect_uri, - ...options, - }; - - const checks = { - state, - nonce, - max_age: maxAge, - code_verifier: codeVerifier, - response_type: responseType, - }; - - const tokenset = await client.callback(opts.redirect_uri, reqParams, checks, this._extras); - - const passReq = this._passReqToCallback; - const loadUserinfo = this._verify.length > (passReq ? 3 : 2) && client.issuer.userinfo_endpoint; - - const args = [tokenset, verified.bind(this)]; - - if (loadUserinfo) { - if (!tokenset.access_token) { - throw new RPError({ - message: 'expected access_token to be returned when asking for userinfo in verify callback', - tokenset, + /** + * 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, marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1() { + let listBlobsHierarchySegmentResponse; + if (!!marker || marker === undefined) { + do { + listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options)); + marker = listBlobsHierarchySegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); + } while (marker); + } }); - } - const userinfo = await client.userinfo(tokenset); - args.splice(1, 0, userinfo); - } - - if (passReq) { - args.unshift(req); - } - - this._verify(...args); - /* end authentication response */ - })().catch((error) => { - if ( - (error instanceof OPError && error.error !== 'server_error' && !error.error.startsWith('invalid')) - || error instanceof RPError - ) { - this.fail(error); - } else { - this.error(error); - } - }); -}; - -module.exports = OpenIDConnectStrategy; - - -/***/ }), - -/***/ 39029: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const base64url = __nccwpck_require__(61827); -const now = __nccwpck_require__(8542); - -class TokenSet { - /** - * @name constructor - * @api public - */ - constructor(values) { - Object.assign(this, values); - } - - /** - * @name expires_in= - * @api public - */ - set expires_in(value) { // eslint-disable-line camelcase - this.expires_at = now() + Number(value); - } - - /** - * @name expires_in - * @api public - */ - get expires_in() { // eslint-disable-line camelcase - return Math.max.apply(null, [this.expires_at - now(), 0]); - } - - /** - * @name expired - * @api public - */ - expired() { - return this.expires_in === 0; - } - - /** - * @name claims - * @api public - */ - claims() { - if (!this.id_token) { - throw new TypeError('id_token not present in TokenSet'); - } - - return JSON.parse(base64url.decode(this.id_token.split('.')[1])); - } -} - -module.exports = TokenSet; - - -/***/ }), - -/***/ 19072: -/***/ ((module) => { - -"use strict"; - - -class CancelError extends Error { - constructor(reason) { - super(reason || 'Promise was canceled'); - this.name = 'CancelError'; - } - - get isCanceled() { - return true; - } -} - -class PCancelable { - static fn(userFn) { - return (...arguments_) => { - return new PCancelable((resolve, reject, onCancel) => { - arguments_.push(onCancel); - // eslint-disable-next-line promise/prefer-await-to-then - userFn(...arguments_).then(resolve, reject); - }); - }; - } - - constructor(executor) { - this._cancelHandlers = []; - this._isPending = true; - this._isCanceled = false; - this._rejectOnCancel = true; - - this._promise = new Promise((resolve, reject) => { - this._reject = reject; - - const onResolve = value => { - if (!this._isCanceled || !onCancel.shouldReject) { - this._isPending = false; - resolve(value); - } - }; - - const onReject = error => { - this._isPending = false; - reject(error); - }; - - const onCancel = handler => { - if (!this._isPending) { - throw new Error('The `onCancel` handler was attached after the promise settled.'); - } - - this._cancelHandlers.push(handler); - }; - - Object.defineProperties(onCancel, { - shouldReject: { - get: () => this._rejectOnCancel, - set: boolean => { - this._rejectOnCancel = boolean; - } - } - }); - - return executor(onResolve, onReject, onCancel); - }); - } - - then(onFulfilled, onRejected) { - // eslint-disable-next-line promise/prefer-await-to-then - return this._promise.then(onFulfilled, onRejected); - } - - catch(onRejected) { - return this._promise.catch(onRejected); - } - - finally(onFinally) { - return this._promise.finally(onFinally); - } - - cancel(reason) { - if (!this._isPending || this._isCanceled) { - return; - } - - this._isCanceled = true; - - if (this._cancelHandlers.length > 0) { - try { - for (const handler of this._cancelHandlers) { - handler(); - } - } catch (error) { - this._reject(error); - return; - } - } - - if (this._rejectOnCancel) { - this._reject(new CancelError(reason)); - } - } - - get isCanceled() { - return this._isCanceled; - } -} - -Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); - -module.exports = PCancelable; -module.exports.CancelError = CancelError; - - -/***/ }), - -/***/ 38714: -/***/ ((module) => { - -"use strict"; - - -function posix(path) { - return path.charAt(0) === '/'; -} - -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} - -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; - - -/***/ }), - -/***/ 20539: -/***/ ((module) => { - -"use strict"; - - -const pathKey = (options = {}) => { - const environment = options.env || process.env; - const platform = options.platform || process.platform; - - if (platform !== 'win32') { - return 'PATH'; - } - - return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; -}; - -module.exports = pathKey; -// TODO: Remove this for the next major release -module.exports["default"] = pathKey; - - -/***/ }), - -/***/ 85644: -/***/ (function(module) { - -// Generated by CoffeeScript 1.12.2 -(function() { - var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; - - if ((typeof performance !== "undefined" && performance !== null) && performance.now) { - module.exports = function() { - return performance.now(); - }; - } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { - module.exports = function() { - return (getNanoSeconds() - nodeLoadTime) / 1e6; - }; - hrtime = process.hrtime; - getNanoSeconds = function() { - var hr; - hr = hrtime(); - return hr[0] * 1e9 + hr[1]; - }; - moduleLoadTime = getNanoSeconds(); - upTime = process.uptime() * 1e9; - nodeLoadTime = moduleLoadTime - upTime; - } else if (Date.now) { - module.exports = function() { - return Date.now() - loadTime; - }; - loadTime = Date.now(); - } else { - module.exports = function() { - return new Date().getTime() - loadTime; - }; - loadTime = new Date().getTime(); - } - -}).call(this); - -//# sourceMappingURL=performance-now.js.map - - -/***/ }), - -/***/ 29975: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */ - - - -var Punycode = __nccwpck_require__(85477); - - -var internals = {}; - - -// -// Read rules from file. -// -internals.rules = (__nccwpck_require__(3704).map)(function (rule) { - - return { - rule: rule, - suffix: rule.replace(/^(\*\.|\!)/, ''), - punySuffix: -1, - wildcard: rule.charAt(0) === '*', - exception: rule.charAt(0) === '!' - }; -}); - - -// -// Check is given string ends with `suffix`. -// -internals.endsWith = function (str, suffix) { - - return str.indexOf(suffix, str.length - suffix.length) !== -1; -}; - - -// -// Find rule for a given domain. -// -internals.findRule = function (domain) { - - var punyDomain = Punycode.toASCII(domain); - return internals.rules.reduce(function (memo, rule) { - - if (rule.punySuffix === -1){ - rule.punySuffix = Punycode.toASCII(rule.suffix); - } - if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) { - return memo; - } - // This has been commented out as it never seems to run. This is because - // sub tlds always appear after their parents and we never find a shorter - // match. - //if (memo) { - // var memoSuffix = Punycode.toASCII(memo.suffix); - // if (memoSuffix.length >= punySuffix.length) { - // return memo; - // } - //} - return rule; - }, null); -}; - - -// -// Error codes and messages. -// -exports.errorCodes = { - DOMAIN_TOO_SHORT: 'Domain name too short.', - DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', - LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', - LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', - LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', - LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', - LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' -}; - - -// -// Validate domain name and throw if not valid. -// -// From wikipedia: -// -// Hostnames are composed of series of labels concatenated with dots, as are all -// domain names. Each label must be between 1 and 63 characters long, and the -// entire hostname (including the delimiting dots) has a maximum of 255 chars. -// -// Allowed chars: -// -// * `a-z` -// * `0-9` -// * `-` but not as a starting or ending character -// * `.` as a separator for the textual portions of a domain name -// -// * http://en.wikipedia.org/wiki/Domain_name -// * http://en.wikipedia.org/wiki/Hostname -// -internals.validate = function (input) { - - // Before we can validate we need to take care of IDNs with unicode chars. - var ascii = Punycode.toASCII(input); - - if (ascii.length < 1) { - return 'DOMAIN_TOO_SHORT'; - } - if (ascii.length > 255) { - return 'DOMAIN_TOO_LONG'; - } - - // Check each part's length and allowed chars. - var labels = ascii.split('.'); - var label; - - for (var i = 0; i < labels.length; ++i) { - label = labels[i]; - if (!label.length) { - return 'LABEL_TOO_SHORT'; - } - if (label.length > 63) { - return 'LABEL_TOO_LONG'; - } - if (label.charAt(0) === '-') { - return 'LABEL_STARTS_WITH_DASH'; - } - if (label.charAt(label.length - 1) === '-') { - return 'LABEL_ENDS_WITH_DASH'; - } - if (!/^[a-z0-9\-]+$/.test(label)) { - return 'LABEL_INVALID_CHARS'; - } - } -}; - - -// -// Public API -// - - -// -// Parse domain. -// -exports.parse = function (input) { - - if (typeof input !== 'string') { - throw new TypeError('Domain name must be a string.'); - } - - // Force domain to lowercase. - var domain = input.slice(0).toLowerCase(); - - // Handle FQDN. - // TODO: Simply remove trailing dot? - if (domain.charAt(domain.length - 1) === '.') { - domain = domain.slice(0, domain.length - 1); - } - - // Validate and sanitise input. - var error = internals.validate(domain); - if (error) { - return { - input: input, - error: { - message: exports.errorCodes[error], - code: error - } - }; - } - - var parsed = { - input: input, - tld: null, - sld: null, - domain: null, - subdomain: null, - listed: false - }; - - var domainParts = domain.split('.'); - - // Non-Internet TLD - if (domainParts[domainParts.length - 1] === 'local') { - return parsed; - } - - var handlePunycode = function () { - - if (!/xn--/.test(domain)) { - return parsed; - } - if (parsed.domain) { - parsed.domain = Punycode.toASCII(parsed.domain); } - if (parsed.subdomain) { - parsed.subdomain = Punycode.toASCII(parsed.subdomain); - } - return parsed; - }; - - var rule = internals.findRule(domain); - - // Unlisted tld. - if (!rule) { - if (domainParts.length < 2) { - return parsed; + /** + * 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, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1() { + var e_2, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const listBlobsHierarchySegmentResponse = _c.value; + const segment = listBlobsHierarchySegmentResponse.segment; + if (segment.blobPrefixes) { + for (const prefix of segment.blobPrefixes) { + yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix)); + } + } + 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 (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_2) throw e_2.error; } + } + }); } - parsed.tld = domainParts.pop(); - parsed.sld = domainParts.pop(); - parsed.domain = [parsed.sld, parsed.tld].join('.'); - if (domainParts.length) { - parsed.subdomain = domainParts.pop(); + /** + * 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(delimiter, options = {}) { + if (delimiter === "") { + throw new RangeError("delimiter should contain one or more characters"); + } + const include = []; + if (options.includeCopy) { + include.push("copy"); + } + if (options.includeDeleted) { + include.push("deleted"); + } + if (options.includeMetadata) { + include.push("metadata"); + } + if (options.includeSnapshots) { + include.push("snapshots"); + } + if (options.includeVersions) { + include.push("versions"); + } + if (options.includeUncommitedBlobs) { + include.push("uncommittedblobs"); + } + if (options.includeTags) { + include.push("tags"); + } + if (options.includeDeletedWithVersions) { + include.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include.push("legalhold"); + } + if (options.prefix === "") { + options.prefix = undefined; + } + const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); + // AsyncIterableIterator to iterate over blob prefixes and blobs + const iter = this.listItemsByHierarchy(delimiter, 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(delimiter, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + }, + }; } - return handlePunycode(); - } - - // At this point we know the public suffix is listed. - parsed.listed = true; - - var tldParts = rule.suffix.split('.'); - var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); - - if (rule.exception) { - privateParts.push(tldParts.shift()); - } - - parsed.tld = tldParts.join('.'); - - if (!privateParts.length) { - return handlePunycode(); - } - - if (rule.wildcard) { - tldParts.unshift(privateParts.pop()); - parsed.tld = tldParts.join('.'); - } - - if (!privateParts.length) { - return handlePunycode(); - } - - parsed.sld = privateParts.pop(); - parsed.domain = [parsed.sld, parsed.tld].join('.'); - - if (privateParts.length) { - parsed.subdomain = privateParts.join('.'); - } - - return handlePunycode(); -}; - - -// -// Get domain. -// -exports.get = function (domain) { - - if (!domain) { - return null; - } - return exports.parse(domain).domain || null; -}; - - -// -// Check whether domain belongs to a known public suffix. -// -exports.isValid = function (domain) { - - var parsed = exports.parse(domain); - return Boolean(parsed.domain && parsed.listed); -}; - - -/***/ }), - -/***/ 18341: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(1223) -var eos = __nccwpck_require__(81205) -var fs = __nccwpck_require__(57147) // we only need fs to get the ReadStream and WriteStream prototypes - -var noop = function () {} -var ancient = /^v?\.0/.test(process.version) - -var isFn = function (fn) { - return typeof fn === 'function' -} - -var isFS = function (stream) { - if (!ancient) return false // newer node version do not need to care about fs is a special way - if (!fs) return false // browser - return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) -} - -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) -} - -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) - - var closed = false - stream.on('close', function () { - closed = true - }) - - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) - - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true - - if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks - if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want - - if (isFn(stream.destroy)) return stream.destroy() - - callback(err || new Error('stream was destroyed')) - } -} - -var call = function (fn) { - fn() -} - -var pipe = function (from, to) { - return from.pipe(to) -} - -var pump = function () { - var streams = Array.prototype.slice.call(arguments) - var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop - - if (Array.isArray(streams[0])) streams = streams[0] - if (streams.length < 2) throw new Error('pump requires two streams per minimum') - - var error - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1 - var writing = i > 0 - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err - if (err) destroys.forEach(call) - if (reading) return - destroys.forEach(call) - callback(error) - }) - }) - - return streams.reduce(pipe) -} - -module.exports = pump - - -/***/ }), - -/***/ 74907: -/***/ ((module) => { - -"use strict"; - - -var replace = String.prototype.replace; -var percentTwenties = /%20/g; - -module.exports = { - 'default': 'RFC3986', - formatters: { - RFC1738: function (value) { - return replace.call(value, percentTwenties, '+'); - }, - RFC3986: function (value) { - return String(value); + /** + * 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, marker, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-findBlobsByTagsSegment", options); + try { + const response = await this.containerContext.filterBlobs(Object.assign({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions))); + 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; } - }, - RFC1738: 'RFC1738', - RFC3986: 'RFC3986' -}; - - -/***/ }), - -/***/ 22760: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var stringify = __nccwpck_require__(79954); -var parse = __nccwpck_require__(33912); -var formats = __nccwpck_require__(74907); - -module.exports = { - formats: formats, - parse: parse, - stringify: stringify -}; - - -/***/ }), - -/***/ 33912: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(72360); - -var has = Object.prototype.hasOwnProperty; - -var defaults = { - allowDots: false, - allowPrototypes: false, - arrayLimit: 20, - decoder: utils.decode, - delimiter: '&', - depth: 5, - parameterLimit: 1000, - plainObjects: false, - strictNullHandling: false -}; - -var parseValues = function parseQueryStringValues(str, options) { - var obj = {}; - var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; - var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; - var parts = cleanStr.split(options.delimiter, limit); - - for (var i = 0; i < parts.length; ++i) { - var part = parts[i]; - - var bracketEqualsPos = part.indexOf(']='); - var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; - - var key, val; - if (pos === -1) { - key = options.decoder(part, defaults.decoder); - val = options.strictNullHandling ? null : ''; - } else { - key = options.decoder(part.slice(0, pos), defaults.decoder); - val = options.decoder(part.slice(pos + 1), defaults.decoder); + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; } - if (has.call(obj, key)) { - obj[key] = [].concat(obj[key]).concat(val); - } else { - obj[key] = val; + finally { + span.end(); } } - - return obj; -}; - -var parseObject = function (chain, val, options) { - var leaf = val; - - for (var i = chain.length - 1; i >= 0; --i) { - var obj; - var root = chain[i]; - - if (root === '[]' && options.parseArrays) { - obj = [].concat(leaf); - } else { - obj = options.plainObjects ? Object.create(null) : {}; - var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; - var index = parseInt(cleanRoot, 10); - if (!options.parseArrays && cleanRoot === '') { - obj = { 0: leaf }; - } else if ( - !isNaN(index) - && root !== cleanRoot - && String(index) === cleanRoot - && index >= 0 - && (options.parseArrays && index <= options.arrayLimit) - ) { - obj = []; - obj[index] = leaf; - } else if (cleanRoot !== '__proto__') { - obj[cleanRoot] = leaf; + /** + * 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, marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1() { + let response; + if (!!marker || marker === undefined) { + do { + response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options)); + response.blobs = response.blobs || []; + marker = response.continuationToken; + yield yield tslib.__await(response); + } while (marker); } - } - - leaf = obj; + }); } - - return leaf; -}; - -var parseKeys = function parseQueryStringKeys(givenKey, val, options) { - if (!givenKey) { - return; + /** + * 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, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1() { + var e_3, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const segment = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_3) throw e_3.error; } + } + }); } - - // Transform dot notation to bracket notation - var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; - - // The regex chunks - - var brackets = /(\[[^[\]]*])/; - var child = /(\[[^[\]]*])/g; - - // Get the parent - - var segment = brackets.exec(key); - var parent = segment ? key.slice(0, segment.index) : key; - - // Stash the parent if it exists - - var keys = []; - if (parent) { - // If we aren't using plain objects, optionally prefix keys - // that would overwrite object prototype properties - if (!options.plainObjects && has.call(Object.prototype, parent)) { - if (!options.allowPrototypes) { - return; + /** + * 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 = {}) { + // AsyncIterableIterator to iterate over blobs + 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)); + }, + }; + } + getContainerNameFromUrl() { + let containerName; + try { + // URL may look like the following + // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer"; + // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` + // http://localhost:10001/devstoreaccount1/containername + const parsedUrl = coreHttp.URLBuilder.parse(this.url); + if (parsedUrl.getHost().split(".")[1] === "blob") { + // "https://myaccount.blob.core.windows.net/containername". + // "https://customdomain.com/containername". + // .getPath() -> /containername + containerName = parsedUrl.getPath().split("/")[1]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername + // .getPath() -> /devstoreaccount1/containername + containerName = parsedUrl.getPath().split("/")[2]; + } + else { + // "https://customdomain.com/containername". + // .getPath() -> /containername + containerName = parsedUrl.getPath().split("/")[1]; + } + // decode the encoded containerName - to get all the special characters that might be present in it + containerName = decodeURIComponent(containerName); + if (!containerName) { + throw new Error("Provided containerName is invalid."); } + return containerName; + } + catch (error) { + throw new Error("Unable to extract containerName with provided information."); } - - keys.push(parent); } - - // Loop through children appending to the array until we hit depth - - var i = 0; - while ((segment = child.exec(key)) !== null && i < options.depth) { - i += 1; - if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { - if (!options.allowPrototypes) { - return; + /** + * 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((resolve) => { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); } - } - keys.push(segment[1]); + const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); + resolve(appendToURLQuery(this.url, sas)); + }); } - - // If there's a remainder, just add whatever is left - - if (segment) { - keys.push('[' + key.slice(segment.index) + ']'); + /** + * 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); } +} - return parseObject(keys, val, options); -}; - -module.exports = function (str, opts) { - var options = opts ? utils.assign({}, opts) : {}; - - if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { - throw new TypeError('Decoder has to be a function.'); +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the + * values are set, this should be serialized with toString and set as the permissions field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + */ +class AccountSASPermissions { + constructor() { + /** + * Permission to read resources and list queues and tables granted. + */ + this.read = false; + /** + * Permission to write resources granted. + */ + this.write = false; + /** + * Permission to create blobs and files granted. + */ + this.delete = false; + /** + * Permission to delete versions granted. + */ + this.deleteVersion = false; + /** + * Permission to list blob containers, blobs, shares, directories, and files granted. + */ + this.list = false; + /** + * Permission to add messages, table entities, and append to blobs granted. + */ + this.add = false; + /** + * Permission to create blobs and files granted. + */ + this.create = false; + /** + * Permissions to update messages and table entities granted. + */ + this.update = false; + /** + * Permission to get and delete messages granted. + */ + this.process = false; + /** + * Specfies Tag access granted. + */ + this.tag = false; + /** + * Permission to filter blobs. + */ + this.filter = false; + /** + * Permission to set immutability policy. + */ + this.setImmutabilityPolicy = false; + /** + * Specifies that Permanent Delete is permitted. + */ + this.permanentDelete = false; } - - options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; - options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; - options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; - options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; - options.parseArrays = options.parseArrays !== false; - options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; - options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; - options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; - options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; - options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; - options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; - - if (str === '' || str === null || typeof str === 'undefined') { - return options.plainObjects ? Object.create(null) : {}; + /** + * 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; } - - var tempObj = typeof str === 'string' ? parseValues(str, options) : str; - var obj = options.plainObjects ? Object.create(null) : {}; - - // Iterate over the keys and setup the new object - - var keys = Object.keys(tempObj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var newObj = parseKeys(key, tempObj[key], options); - obj = utils.merge(obj, newObj, options); + /** + * 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; } - - return utils.compact(obj); -}; - - -/***/ }), - -/***/ 79954: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(72360); -var formats = __nccwpck_require__(74907); - -var arrayPrefixGenerators = { - brackets: function brackets(prefix) { - return prefix + '[]'; - }, - indices: function indices(prefix, key) { - return prefix + '[' + key + ']'; - }, - repeat: function repeat(prefix) { - return prefix; + /** + * 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() { + // The order of the characters should be as specified here to ensure correctness: + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + // Use a string array instead of string concatenating += operator for performance + 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 isArray = Array.isArray; -var push = Array.prototype.push; -var pushToArray = function (arr, valueOrArray) { - push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); -}; - -var toISO = Date.prototype.toISOString; - -var defaults = { - delimiter: '&', - encode: true, - encoder: utils.encode, - encodeValuesOnly: false, - serializeDate: function serializeDate(date) { - return toISO.call(date); - }, - skipNulls: false, - strictNullHandling: false -}; +} -var stringify = function stringify( - object, - prefix, - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly -) { - var obj = object; - if (typeof filter === 'function') { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate(obj); +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the + * values are set, this should be serialized with toString and set as the resources field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but + * the order of the resources is particular and this class guarantees correctness. + */ +class AccountSASResourceTypes { + constructor() { + /** + * Permission to access service level APIs granted. + */ + this.service = false; + /** + * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. + */ + this.container = false; + /** + * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. + */ + this.object = false; } - - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; + /** + * 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}`); + } } - - obj = ''; + return accountSASResourceTypes; } - - if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { - if (encoder) { - var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); - return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; + /** + * 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 [formatter(prefix) + '=' + formatter(String(obj))]; + return resourceTypes.join(""); } +} - var values = []; - - if (typeof obj === 'undefined') { - return values; +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant access to that service. Once all the + * values are set, this should be serialized with toString and set as the services field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but + * the order of the services is particular and this class guarantees correctness. + */ +class AccountSASServices { + constructor() { + /** + * Permission to access blob resources granted. + */ + this.blob = false; + /** + * Permission to access file resources granted. + */ + this.file = false; + /** + * Permission to access queue resources granted. + */ + this.queue = false; + /** + * Permission to access table resources granted. + */ + this.table = false; } - - var objKeys; - if (isArray(filter)) { - objKeys = filter; - } else { - var keys = Object.keys(obj); - objKeys = sort ? keys.sort(sort) : keys; + /** + * 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; } - - for (var i = 0; i < objKeys.length; ++i) { - var key = objKeys[i]; - - if (skipNulls && obj[key] === null) { - continue; + /** + * Converts the given services to a string. + * + */ + toString() { + const services = []; + if (this.blob) { + services.push("b"); } - - if (isArray(obj)) { - pushToArray(values, stringify( - obj[key], - generateArrayPrefix(prefix, key), - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); - } else { - pushToArray(values, stringify( - obj[key], - prefix + (allowDots ? '.' + key : '[' + key + ']'), - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); + if (this.table) { + services.push("t"); + } + if (this.queue) { + services.push("q"); } + if (this.file) { + services.push("f"); + } + return services.join(""); } +} - return values; -}; - -module.exports = function (object, opts) { - var obj = object; - var options = opts ? utils.assign({}, opts) : {}; - - if (options.encoder !== null && typeof options.encoder !== 'undefined' && typeof options.encoder !== 'function') { - throw new TypeError('Encoder has to be a function.'); +// Copyright (c) Microsoft Corporation. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual + * REST request. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @param accountSASSignatureValues - + * @param sharedKeyCredential - + */ +function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + const version = accountSASSignatureValues.version + ? accountSASSignatureValues.version + : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.setImmutabilityPolicy && + version < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); } - - var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; - var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; - var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; - var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; - var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; - var sort = typeof options.sort === 'function' ? options.sort : null; - var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; - var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; - var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; - if (typeof options.format === 'undefined') { - options.format = formats['default']; - } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { - throw new TypeError('Unknown format option provided.'); + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); } - var formatter = formats.formatters[options.format]; - var objKeys; - var filter; - - if (typeof options.filter === 'function') { - filter = options.filter; - obj = filter('', obj); - } else if (isArray(options.filter)) { - filter = options.filter; - objKeys = filter; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.permanentDelete && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'y' permission."); } - - var keys = []; - - if (typeof obj !== 'object' || obj === null) { - return ''; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); } - - var arrayFormat; - if (options.arrayFormat in arrayPrefixGenerators) { - arrayFormat = options.arrayFormat; - } else if ('indices' in options) { - arrayFormat = options.indices ? 'indices' : 'repeat'; - } else { - arrayFormat = 'indices'; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.filter && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); } - - var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; - - if (!objKeys) { - objKeys = Object.keys(obj); + if (accountSASSignatureValues.encryptionScope && version < "2020-12-06") { + throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); } - - if (sort) { - objKeys.sort(sort); + const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + let stringToSign; + if (version >= "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 : "", + version, + 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 : "", + version, + "", // Account SAS requires an additional newline character + ].join("\n"); + } + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, accountSASSignatureValues.encryptionScope); +} - for (var i = 0; i < objKeys.length; ++i) { - var key = objKeys[i]; - - if (skipNulls && obj[key] === null) { - continue; +/** + * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you + * to manipulate blob containers. + */ +class BlobServiceClient extends StorageClient { + constructor(url, credentialOrPipeline, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { + pipeline = credentialOrPipeline; } - pushToArray(keys, stringify( - obj[key], - key, - generateArrayPrefix, - strictNullHandling, - skipNulls, - encode ? encoder : null, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); - } - - var joined = keys.join(delimiter); - var prefix = options.addQueryPrefix === true ? '?' : ''; - - return joined.length > 0 ? prefix + joined : ''; -}; - - -/***/ }), - -/***/ 72360: -/***/ ((module) => { - -"use strict"; - - -var has = Object.prototype.hasOwnProperty; - -var hexTable = (function () { - var array = []; - for (var i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || + credentialOrPipeline instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipeline)) { + pipeline = newPipeline(credentialOrPipeline, options); + } + else { + // The second parameter is undefined. Use anonymous credential + pipeline = newPipeline(new AnonymousCredential(), options); + } + super(url, pipeline); + this.serviceContext = new Service(this.storageClientContext); } - - return array; -}()); - -var compactQueue = function compactQueue(queue) { - var obj; - - while (queue.length) { - var item = queue.pop(); - obj = item.obj[item.prop]; - - if (Array.isArray(obj)) { - var compacted = []; - - for (var j = 0; j < obj.length; ++j) { - if (typeof obj[j] !== 'undefined') { - compacted.push(obj[j]); + /** + * + * 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, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + options = options || {}; + const extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreHttp.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + if (!options.proxyOptions) { + options.proxyOptions = coreHttp.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"); } - - item.obj[item.prop] = compacted; } - } - - return obj; -}; - -var arrayToObject = function arrayToObject(source, options) { - var obj = options && options.plainObjects ? Object.create(null) : {}; - for (var i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; + else if (extractedCreds.kind === "SASConnString") { + const pipeline = newPipeline(new AnonymousCredential(), options); + return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); } - } - - return obj; -}; - -var merge = function merge(target, source, options) { - if (!source) { - return target; - } - - if (typeof source !== 'object') { - if (Array.isArray(target)) { - target.push(source); - } else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { - target[source] = true; - } - } else { - return [target, source]; + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } - - return target; - } - - if (!target || typeof target !== 'object') { - return [target].concat(source); } - - var mergeTarget = target; - if (Array.isArray(target) && !Array.isArray(source)) { - mergeTarget = arrayToObject(target, options); - } - - if (Array.isArray(target) && Array.isArray(source)) { - source.forEach(function (item, i) { - if (has.call(target, i)) { - var targetItem = target[i]; - if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { - target[i] = merge(targetItem, item, options); - } else { - target.push(item); - } - } else { - target[i] = item; - } - }); - return target; + /** + * 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); } - - return Object.keys(source).reduce(function (acc, key) { - var value = source[key]; - - if (has.call(acc, key)) { - acc[key] = merge(acc[key], value, options); - } else { - acc[key] = value; + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-createContainer", options); + try { + const containerClient = this.getContainerClient(containerName); + const containerCreateResponse = await containerClient.create(updatedOptions); + return { + containerClient, + containerCreateResponse, + }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); } - return acc; - }, mergeTarget); -}; - -var assign = function assignSingleSource(target, source) { - return Object.keys(source).reduce(function (acc, key) { - acc[key] = source[key]; - return acc; - }, target); -}; - -var decode = function (str) { - try { - return decodeURIComponent(str.replace(/\+/g, ' ')); - } catch (e) { - return str; } -}; - -var encode = function encode(str) { - // This code was originally written by Brian White (mscdex) for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-deleteContainer", options); + try { + const containerClient = this.getContainerClient(containerName); + return await containerClient.delete(updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - - var string = typeof str === 'string' ? str : String(str); - - var out = ''; - for (var i = 0; i < string.length; ++i) { - var c = string.charCodeAt(i); - - if ( - c === 0x2D // - - || c === 0x2E // . - || c === 0x5F // _ - || c === 0x7E // ~ - || (c >= 0x30 && c <= 0x39) // 0-9 - || (c >= 0x41 && c <= 0x5A) // a-z - || (c >= 0x61 && c <= 0x7A) // A-Z - ) { - out += string.charAt(i); - continue; + /** + * 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(deletedContainerName, deletedContainerVersion, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-undeleteContainer", options); + try { + const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); + // Hack to access a protected member. + const containerContext = new Container(containerClient["storageClientContext"]); + const containerUndeleteResponse = await containerContext.restore(Object.assign({ deletedContainerName, + deletedContainerVersion }, updatedOptions)); + return { containerClient, containerUndeleteResponse }; } - - if (c < 0x80) { - out = out + hexTable[c]; - continue; + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } + } + /** + * 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(sourceContainerName, destinationContainerName, options = {}) { + var _a; + const { span, updatedOptions } = createSpan("BlobServiceClient-renameContainer", options); + try { + const containerClient = this.getContainerClient(destinationContainerName); + // Hack to access a protected member. + const containerContext = new Container(containerClient["storageClientContext"]); + const containerRenameResponse = await containerContext.rename(sourceContainerName, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId })); + return { containerClient, containerRenameResponse }; } - - if (c < 0x800) { - out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); - continue; + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; } - - if (c < 0xD800 || c >= 0xE000) { - out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); - continue; + finally { + span.end(); } - - i += 1; - c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); - /* eslint operator-linebreak: [2, "before"] */ - out += hexTable[0xF0 | (c >> 18)] - + hexTable[0x80 | ((c >> 12) & 0x3F)] - + hexTable[0x80 | ((c >> 6) & 0x3F)] - + hexTable[0x80 | (c & 0x3F)]; } - - return out; -}; - -var compact = function compact(value) { - var queue = [{ obj: { o: value }, prop: 'o' }]; - var refs = []; - - for (var i = 0; i < queue.length; ++i) { - var item = queue[i]; - var obj = item.obj[item.prop]; - - var keys = Object.keys(obj); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - var val = obj[key]; - if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj: obj, prop: key }); - refs.push(val); - } + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getProperties", options); + try { + return await this.serviceContext.getProperties(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); } } - - return compactQueue(queue); -}; - -var isRegExp = function isRegExp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -}; - -var isBuffer = function isBuffer(obj) { - if (obj === null || typeof obj === 'undefined') { - return false; + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-setProperties", options); + try { + return await this.serviceContext.setProperties(properties, Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -}; - -module.exports = { - arrayToObject: arrayToObject, - assign: assign, - compact: compact, - decode: decode, - encode: encode, - isBuffer: isBuffer, - isRegExp: isRegExp, - merge: merge -}; - - -/***/ }), - -/***/ 49273: -/***/ ((module) => { - -"use strict"; - - -class QuickLRU { - constructor(options = {}) { - if (!(options.maxSize && options.maxSize > 0)) { - throw new TypeError('`maxSize` must be a number greater than 0'); - } - - this.maxSize = options.maxSize; - this.onEviction = options.onEviction; - this.cache = new Map(); - this.oldCache = new Map(); - this._size = 0; - } - - _set(key, value) { - this.cache.set(key, value); - this._size++; - - if (this._size >= this.maxSize) { - this._size = 0; - - if (typeof this.onEviction === 'function') { - for (const [key, value] of this.oldCache.entries()) { - this.onEviction(key, value); - } - } - - this.oldCache = this.cache; - this.cache = new Map(); - } - } - - get(key) { - if (this.cache.has(key)) { - return this.cache.get(key); - } - - if (this.oldCache.has(key)) { - const value = this.oldCache.get(key); - this.oldCache.delete(key); - this._set(key, value); - return value; - } - } - - set(key, value) { - if (this.cache.has(key)) { - this.cache.set(key, value); - } else { - this._set(key, value); - } - - return this; - } - - has(key) { - return this.cache.has(key) || this.oldCache.has(key); - } - - peek(key) { - if (this.cache.has(key)) { - return this.cache.get(key); - } - - if (this.oldCache.has(key)) { - return this.oldCache.get(key); - } - } - - delete(key) { - const deleted = this.cache.delete(key); - if (deleted) { - this._size--; - } - - return this.oldCache.delete(key) || deleted; - } - - clear() { - this.cache.clear(); - this.oldCache.clear(); - this._size = 0; - } - - * keys() { - for (const [key] of this) { - yield key; - } - } - - * values() { - for (const [, value] of this) { - yield value; - } - } - - * [Symbol.iterator]() { - for (const item of this.cache) { - yield item; - } - - for (const item of this.oldCache) { - const [key] = item; - if (!this.cache.has(key)) { - yield item; - } - } - } - - get size() { - let oldCacheSize = 0; - for (const key of this.oldCache.keys()) { - if (!this.cache.has(key)) { - oldCacheSize++; - } - } - - return Math.min(this._size + oldCacheSize, this.maxSize); - } -} - -module.exports = QuickLRU; - - -/***/ }), - -/***/ 29977: -/***/ (() => { - -/*! ***************************************************************************** -Copyright (C) Microsoft. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -var Reflect; -(function (Reflect) { - // Metadata Proposal - // https://rbuckton.github.io/reflect-metadata/ - (function (factory) { - var root = typeof global === "object" ? global : - typeof self === "object" ? self : - typeof this === "object" ? this : - Function("return this;")(); - var exporter = makeExporter(Reflect); - if (typeof root.Reflect === "undefined") { - root.Reflect = Reflect; + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getStatistics", options); + try { + return await this.serviceContext.getStatistics(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } - else { - exporter = makeExporter(root.Reflect, exporter); + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; } - factory(exporter); - function makeExporter(target, previous) { - return function (key, value) { - if (typeof target[key] !== "function") { - Object.defineProperty(target, key, { configurable: true, writable: true, value: value }); - } - if (previous) - previous(key, value); - }; + finally { + span.end(); } - })(function (exporter) { - var hasOwn = Object.prototype.hasOwnProperty; - // feature test for Symbol support - var supportsSymbol = typeof Symbol === "function"; - var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive"; - var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator"; - var supportsCreate = typeof Object.create === "function"; // feature test for Object.create support - var supportsProto = { __proto__: [] } instanceof Array; // feature test for __proto__ support - var downLevel = !supportsCreate && !supportsProto; - var HashMap = { - // create an object in dictionary mode (a.k.a. "slow" mode in v8) - create: supportsCreate - ? function () { return MakeDictionary(Object.create(null)); } - : supportsProto - ? function () { return MakeDictionary({ __proto__: null }); } - : function () { return MakeDictionary({}); }, - has: downLevel - ? function (map, key) { return hasOwn.call(map, key); } - : function (map, key) { return key in map; }, - get: downLevel - ? function (map, key) { return hasOwn.call(map, key) ? map[key] : undefined; } - : function (map, key) { return map[key]; }, - }; - // Load global or shim versions of Map, Set, and WeakMap - var functionPrototype = Object.getPrototypeOf(Function); - var usePolyfill = typeof process === "object" && process.env && process.env["REFLECT_METADATA_USE_MAP_POLYFILL"] === "true"; - var _Map = !usePolyfill && typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill(); - var _Set = !usePolyfill && typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill(); - var _WeakMap = !usePolyfill && typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill(); - // [[Metadata]] internal slot - // https://rbuckton.github.io/reflect-metadata/#ordinary-object-internal-methods-and-internal-slots - var Metadata = new _WeakMap(); - /** - * Applies a set of decorators to a property of a target object. - * @param decorators An array of decorators. - * @param target The target object. - * @param propertyKey (Optional) The property key to decorate. - * @param attributes (Optional) The property descriptor for the target key. - * @remarks Decorators are applied in reverse order. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * Example = Reflect.decorate(decoratorsArray, Example); - * - * // property (on constructor) - * Reflect.decorate(decoratorsArray, Example, "staticProperty"); - * - * // property (on prototype) - * Reflect.decorate(decoratorsArray, Example.prototype, "property"); - * - * // method (on constructor) - * Object.defineProperty(Example, "staticMethod", - * Reflect.decorate(decoratorsArray, Example, "staticMethod", - * Object.getOwnPropertyDescriptor(Example, "staticMethod"))); - * - * // method (on prototype) - * Object.defineProperty(Example.prototype, "method", - * Reflect.decorate(decoratorsArray, Example.prototype, "method", - * Object.getOwnPropertyDescriptor(Example.prototype, "method"))); - * - */ - function decorate(decorators, target, propertyKey, attributes) { - if (!IsUndefined(propertyKey)) { - if (!IsArray(decorators)) - throw new TypeError(); - if (!IsObject(target)) - throw new TypeError(); - if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes)) - throw new TypeError(); - if (IsNull(attributes)) - attributes = undefined; - propertyKey = ToPropertyKey(propertyKey); - return DecorateProperty(decorators, target, propertyKey, attributes); - } - else { - if (!IsArray(decorators)) - throw new TypeError(); - if (!IsConstructor(target)) - throw new TypeError(); - return DecorateConstructor(decorators, target); - } + } + /** + * 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 = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getAccountInfo", options); + try { + return await this.serviceContext.getAccountInfo(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } - exporter("decorate", decorate); - // 4.1.2 Reflect.metadata(metadataKey, metadataValue) - // https://rbuckton.github.io/reflect-metadata/#reflect.metadata - /** - * A default metadata decorator factory that can be used on a class, class member, or parameter. - * @param metadataKey The key for the metadata entry. - * @param metadataValue The value for the metadata entry. - * @returns A decorator function. - * @remarks - * If `metadataKey` is already defined for the target and target key, the - * metadataValue for that key will be overwritten. - * @example - * - * // constructor - * @Reflect.metadata(key, value) - * class Example { - * } - * - * // property (on constructor, TypeScript only) - * class Example { - * @Reflect.metadata(key, value) - * static staticProperty; - * } - * - * // property (on prototype, TypeScript only) - * class Example { - * @Reflect.metadata(key, value) - * property; - * } - * - * // method (on constructor) - * class Example { - * @Reflect.metadata(key, value) - * static staticMethod() { } - * } - * - * // method (on prototype) - * class Example { - * @Reflect.metadata(key, value) - * method() { } - * } - * - */ - function metadata(metadataKey, metadataValue) { - function decorator(target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) - throw new TypeError(); - OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); - } - return decorator; + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; } - exporter("metadata", metadata); - /** - * Define a unique metadata entry on the target. - * @param metadataKey A key used to store and retrieve metadata. - * @param metadataValue A value that contains attached metadata. - * @param target The target object on which to define metadata. - * @param propertyKey (Optional) The property key for the target. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * Reflect.defineMetadata("custom:annotation", options, Example); - * - * // property (on constructor) - * Reflect.defineMetadata("custom:annotation", options, Example, "staticProperty"); - * - * // property (on prototype) - * Reflect.defineMetadata("custom:annotation", options, Example.prototype, "property"); - * - * // method (on constructor) - * Reflect.defineMetadata("custom:annotation", options, Example, "staticMethod"); - * - * // method (on prototype) - * Reflect.defineMetadata("custom:annotation", options, Example.prototype, "method"); - * - * // decorator factory as metadata-producing annotation. - * function MyAnnotation(options): Decorator { - * return (target, key?) => Reflect.defineMetadata("custom:annotation", options, target, key); - * } - * - */ - function defineMetadata(metadataKey, metadataValue, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); - } - exporter("defineMetadata", defineMetadata); - /** - * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined. - * @param metadataKey A key used to store and retrieve metadata. - * @param target The target object on which the metadata is defined. - * @param propertyKey (Optional) The property key for the target. - * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * result = Reflect.hasMetadata("custom:annotation", Example); - * - * // property (on constructor) - * result = Reflect.hasMetadata("custom:annotation", Example, "staticProperty"); - * - * // property (on prototype) - * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "property"); - * - * // method (on constructor) - * result = Reflect.hasMetadata("custom:annotation", Example, "staticMethod"); - * - * // method (on prototype) - * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "method"); - * - */ - function hasMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryHasMetadata(metadataKey, target, propertyKey); - } - exporter("hasMetadata", hasMetadata); - /** - * Gets a value indicating whether the target object has the provided metadata key defined. - * @param metadataKey A key used to store and retrieve metadata. - * @param target The target object on which the metadata is defined. - * @param propertyKey (Optional) The property key for the target. - * @returns `true` if the metadata key was defined on the target object; otherwise, `false`. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * result = Reflect.hasOwnMetadata("custom:annotation", Example); - * - * // property (on constructor) - * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticProperty"); - * - * // property (on prototype) - * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "property"); - * - * // method (on constructor) - * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticMethod"); - * - * // method (on prototype) - * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "method"); - * - */ - function hasOwnMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey); - } - exporter("hasOwnMetadata", hasOwnMetadata); - /** - * Gets the metadata value for the provided metadata key on the target object or its prototype chain. - * @param metadataKey A key used to store and retrieve metadata. - * @param target The target object on which the metadata is defined. - * @param propertyKey (Optional) The property key for the target. - * @returns The metadata value for the metadata key if found; otherwise, `undefined`. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * result = Reflect.getMetadata("custom:annotation", Example); - * - * // property (on constructor) - * result = Reflect.getMetadata("custom:annotation", Example, "staticProperty"); - * - * // property (on prototype) - * result = Reflect.getMetadata("custom:annotation", Example.prototype, "property"); - * - * // method (on constructor) - * result = Reflect.getMetadata("custom:annotation", Example, "staticMethod"); - * - * // method (on prototype) - * result = Reflect.getMetadata("custom:annotation", Example.prototype, "method"); - * - */ - function getMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryGetMetadata(metadataKey, target, propertyKey); - } - exporter("getMetadata", getMetadata); - /** - * Gets the metadata value for the provided metadata key on the target object. - * @param metadataKey A key used to store and retrieve metadata. - * @param target The target object on which the metadata is defined. - * @param propertyKey (Optional) The property key for the target. - * @returns The metadata value for the metadata key if found; otherwise, `undefined`. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * result = Reflect.getOwnMetadata("custom:annotation", Example); - * - * // property (on constructor) - * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticProperty"); - * - * // property (on prototype) - * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "property"); - * - * // method (on constructor) - * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticMethod"); - * - * // method (on prototype) - * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "method"); - * - */ - function getOwnMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey); - } - exporter("getOwnMetadata", getOwnMetadata); - /** - * Gets the metadata keys defined on the target object or its prototype chain. - * @param target The target object on which the metadata is defined. - * @param propertyKey (Optional) The property key for the target. - * @returns An array of unique metadata keys. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * result = Reflect.getMetadataKeys(Example); - * - * // property (on constructor) - * result = Reflect.getMetadataKeys(Example, "staticProperty"); - * - * // property (on prototype) - * result = Reflect.getMetadataKeys(Example.prototype, "property"); - * - * // method (on constructor) - * result = Reflect.getMetadataKeys(Example, "staticMethod"); - * - * // method (on prototype) - * result = Reflect.getMetadataKeys(Example.prototype, "method"); - * - */ - function getMetadataKeys(target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryMetadataKeys(target, propertyKey); - } - exporter("getMetadataKeys", getMetadataKeys); - /** - * Gets the unique metadata keys defined on the target object. - * @param target The target object on which the metadata is defined. - * @param propertyKey (Optional) The property key for the target. - * @returns An array of unique metadata keys. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * result = Reflect.getOwnMetadataKeys(Example); - * - * // property (on constructor) - * result = Reflect.getOwnMetadataKeys(Example, "staticProperty"); - * - * // property (on prototype) - * result = Reflect.getOwnMetadataKeys(Example.prototype, "property"); - * - * // method (on constructor) - * result = Reflect.getOwnMetadataKeys(Example, "staticMethod"); - * - * // method (on prototype) - * result = Reflect.getOwnMetadataKeys(Example.prototype, "method"); - * - */ - function getOwnMetadataKeys(target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryOwnMetadataKeys(target, propertyKey); - } - exporter("getOwnMetadataKeys", getOwnMetadataKeys); - /** - * Deletes the metadata entry from the target object with the provided key. - * @param metadataKey A key used to store and retrieve metadata. - * @param target The target object on which the metadata is defined. - * @param propertyKey (Optional) The property key for the target. - * @returns `true` if the metadata entry was found and deleted; otherwise, false. - * @example - * - * class Example { - * // property declarations are not part of ES6, though they are valid in TypeScript: - * // static staticProperty; - * // property; - * - * constructor(p) { } - * static staticMethod(p) { } - * method(p) { } - * } - * - * // constructor - * result = Reflect.deleteMetadata("custom:annotation", Example); - * - * // property (on constructor) - * result = Reflect.deleteMetadata("custom:annotation", Example, "staticProperty"); - * - * // property (on prototype) - * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "property"); - * - * // method (on constructor) - * result = Reflect.deleteMetadata("custom:annotation", Example, "staticMethod"); - * - * // method (on prototype) - * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "method"); - * - */ - function deleteMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - var metadataMap = GetOrCreateMetadataMap(target, propertyKey, /*Create*/ false); - if (IsUndefined(metadataMap)) - return false; - if (!metadataMap.delete(metadataKey)) - return false; - if (metadataMap.size > 0) - return true; - var targetMetadata = Metadata.get(target); - targetMetadata.delete(propertyKey); - if (targetMetadata.size > 0) - return true; - Metadata.delete(target); - return true; + finally { + span.end(); } - exporter("deleteMetadata", deleteMetadata); - function DecorateConstructor(decorators, target) { - for (var i = decorators.length - 1; i >= 0; --i) { - var decorator = decorators[i]; - var decorated = decorator(target); - if (!IsUndefined(decorated) && !IsNull(decorated)) { - if (!IsConstructor(decorated)) - throw new TypeError(); - target = decorated; - } - } - return target; + } + /** + * 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(marker, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-listContainersSegment", options); + try { + return await this.serviceContext.listContainersSegment(Object.assign(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include }), convertTracingToRequestOptionsBase(updatedOptions))); } - function DecorateProperty(decorators, target, propertyKey, descriptor) { - for (var i = decorators.length - 1; i >= 0; --i) { - var decorator = decorators[i]; - var decorated = decorator(target, propertyKey, descriptor); - if (!IsUndefined(decorated) && !IsNull(decorated)) { - if (!IsObject(decorated)) - throw new TypeError(); - descriptor = decorated; - } - } - return descriptor; + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; } - function GetOrCreateMetadataMap(O, P, Create) { - var targetMetadata = Metadata.get(O); - if (IsUndefined(targetMetadata)) { - if (!Create) - return undefined; - targetMetadata = new _Map(); - Metadata.set(O, targetMetadata); - } - var metadataMap = targetMetadata.get(P); - if (IsUndefined(metadataMap)) { - if (!Create) - return undefined; - metadataMap = new _Map(); - targetMetadata.set(P, metadataMap); - } - return metadataMap; + finally { + span.end(); } - // 3.1.1.1 OrdinaryHasMetadata(MetadataKey, O, P) - // https://rbuckton.github.io/reflect-metadata/#ordinaryhasmetadata - function OrdinaryHasMetadata(MetadataKey, O, P) { - var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) - return true; - var parent = OrdinaryGetPrototypeOf(O); - if (!IsNull(parent)) - return OrdinaryHasMetadata(MetadataKey, parent, P); - return false; + } + /** + * 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, marker, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-findBlobsByTagsSegment", options); + try { + const response = await this.serviceContext.filterBlobs(Object.assign({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions))); + 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; } - // 3.1.2.1 OrdinaryHasOwnMetadata(MetadataKey, O, P) - // https://rbuckton.github.io/reflect-metadata/#ordinaryhasownmetadata - function OrdinaryHasOwnMetadata(MetadataKey, O, P) { - var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); - if (IsUndefined(metadataMap)) - return false; - return ToBoolean(metadataMap.has(MetadataKey)); - } - // 3.1.3.1 OrdinaryGetMetadata(MetadataKey, O, P) - // https://rbuckton.github.io/reflect-metadata/#ordinarygetmetadata - function OrdinaryGetMetadata(MetadataKey, O, P) { - var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) - return OrdinaryGetOwnMetadata(MetadataKey, O, P); - var parent = OrdinaryGetPrototypeOf(O); - if (!IsNull(parent)) - return OrdinaryGetMetadata(MetadataKey, parent, P); - return undefined; + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; } - // 3.1.4.1 OrdinaryGetOwnMetadata(MetadataKey, O, P) - // https://rbuckton.github.io/reflect-metadata/#ordinarygetownmetadata - function OrdinaryGetOwnMetadata(MetadataKey, O, P) { - var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); - if (IsUndefined(metadataMap)) - return undefined; - return metadataMap.get(MetadataKey); - } - // 3.1.5.1 OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) - // https://rbuckton.github.io/reflect-metadata/#ordinarydefineownmetadata - function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) { - var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ true); - metadataMap.set(MetadataKey, MetadataValue); - } - // 3.1.6.1 OrdinaryMetadataKeys(O, P) - // https://rbuckton.github.io/reflect-metadata/#ordinarymetadatakeys - function OrdinaryMetadataKeys(O, P) { - var ownKeys = OrdinaryOwnMetadataKeys(O, P); - var parent = OrdinaryGetPrototypeOf(O); - if (parent === null) - return ownKeys; - var parentKeys = OrdinaryMetadataKeys(parent, P); - if (parentKeys.length <= 0) - return ownKeys; - if (ownKeys.length <= 0) - return parentKeys; - var set = new _Set(); - var keys = []; - for (var _i = 0, ownKeys_1 = ownKeys; _i < ownKeys_1.length; _i++) { - var key = ownKeys_1[_i]; - var hasKey = set.has(key); - if (!hasKey) { - set.add(key); - keys.push(key); - } + finally { + span.end(); + } + } + /** + * 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, marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1() { + let response; + if (!!marker || marker === undefined) { + do { + response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options)); + response.blobs = response.blobs || []; + marker = response.continuationToken; + yield yield tslib.__await(response); + } while (marker); } - for (var _a = 0, parentKeys_1 = parentKeys; _a < parentKeys_1.length; _a++) { - var key = parentKeys_1[_a]; - var hasKey = set.has(key); - if (!hasKey) { - set.add(key); - keys.push(key); + }); + } + /** + * 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, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1() { + var e_1, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const segment = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } } - return keys; - } - // 3.1.7.1 OrdinaryOwnMetadataKeys(O, P) - // https://rbuckton.github.io/reflect-metadata/#ordinaryownmetadatakeys - function OrdinaryOwnMetadataKeys(O, P) { - var keys = []; - var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); - if (IsUndefined(metadataMap)) - return keys; - var keysObj = metadataMap.keys(); - var iterator = GetIterator(keysObj); - var k = 0; - while (true) { - var next = IteratorStep(iterator); - if (!next) { - keys.length = k; - return keys; - } - var nextValue = IteratorValue(next); + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { try { - keys[k] = nextValue; - } - catch (e) { - try { - IteratorClose(iterator); - } - finally { - throw e; - } + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } - k++; - } - } - // 6 ECMAScript Data Typ0es and Values - // https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values - function Type(x) { - if (x === null) - return 1 /* Null */; - switch (typeof x) { - case "undefined": return 0 /* Undefined */; - case "boolean": return 2 /* Boolean */; - case "string": return 3 /* String */; - case "symbol": return 4 /* Symbol */; - case "number": return 5 /* Number */; - case "object": return x === null ? 1 /* Null */ : 6 /* Object */; - default: return 6 /* Object */; - } - } - // 6.1.1 The Undefined Type - // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-undefined-type - function IsUndefined(x) { - return x === undefined; - } - // 6.1.2 The Null Type - // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-null-type - function IsNull(x) { - return x === null; - } - // 6.1.5 The Symbol Type - // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-symbol-type - function IsSymbol(x) { - return typeof x === "symbol"; - } - // 6.1.7 The Object Type - // https://tc39.github.io/ecma262/#sec-object-type - function IsObject(x) { - return typeof x === "object" ? x !== null : typeof x === "function"; - } - // 7.1 Type Conversion - // https://tc39.github.io/ecma262/#sec-type-conversion - // 7.1.1 ToPrimitive(input [, PreferredType]) - // https://tc39.github.io/ecma262/#sec-toprimitive - function ToPrimitive(input, PreferredType) { - switch (Type(input)) { - case 0 /* Undefined */: return input; - case 1 /* Null */: return input; - case 2 /* Boolean */: return input; - case 3 /* String */: return input; - case 4 /* Symbol */: return input; - case 5 /* Number */: return input; + finally { if (e_1) throw e_1.error; } } - var hint = PreferredType === 3 /* String */ ? "string" : PreferredType === 5 /* Number */ ? "number" : "default"; - var exoticToPrim = GetMethod(input, toPrimitiveSymbol); - if (exoticToPrim !== undefined) { - var result = exoticToPrim.call(input, hint); - if (IsObject(result)) - throw new TypeError(); - return result; + }); + } + /** + * 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 = {}) { + // AsyncIterableIterator to iterate over blobs + 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, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1() { + let listContainersSegmentResponse; + if (!!marker || marker === undefined) { + do { + listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker, options)); + listContainersSegmentResponse.containerItems = + listContainersSegmentResponse.containerItems || []; + marker = listContainersSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); + } while (marker); } - return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint); - } - // 7.1.1.1 OrdinaryToPrimitive(O, hint) - // https://tc39.github.io/ecma262/#sec-ordinarytoprimitive - function OrdinaryToPrimitive(O, hint) { - if (hint === "string") { - var toString_1 = O.toString; - if (IsCallable(toString_1)) { - var result = toString_1.call(O); - if (!IsObject(result)) - return result; - } - var valueOf = O.valueOf; - if (IsCallable(valueOf)) { - var result = valueOf.call(O); - if (!IsObject(result)) - return result; + }); + } + /** + * Returns an AsyncIterableIterator for Container Items + * + * @param options - Options to list containers operation. + */ + listItems(options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItems_1() { + var e_2, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const segment = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); } } - else { - var valueOf = O.valueOf; - if (IsCallable(valueOf)) { - var result = valueOf.call(O); - if (!IsObject(result)) - return result; - } - var toString_2 = O.toString; - if (IsCallable(toString_2)) { - var result = toString_2.call(O); - if (!IsObject(result)) - return result; + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } + finally { if (e_2) throw e_2.error; } } - throw new TypeError(); - } - // 7.1.2 ToBoolean(argument) - // https://tc39.github.io/ecma262/2016/#sec-toboolean - function ToBoolean(argument) { - return !!argument; - } - // 7.1.12 ToString(argument) - // https://tc39.github.io/ecma262/#sec-tostring - function ToString(argument) { - return "" + argument; - } - // 7.1.14 ToPropertyKey(argument) - // https://tc39.github.io/ecma262/#sec-topropertykey - function ToPropertyKey(argument) { - var key = ToPrimitive(argument, 3 /* String */); - if (IsSymbol(key)) - return key; - return ToString(key); - } - // 7.2 Testing and Comparison Operations - // https://tc39.github.io/ecma262/#sec-testing-and-comparison-operations - // 7.2.2 IsArray(argument) - // https://tc39.github.io/ecma262/#sec-isarray - function IsArray(argument) { - return Array.isArray - ? Array.isArray(argument) - : argument instanceof Object - ? argument instanceof Array - : Object.prototype.toString.call(argument) === "[object Array]"; - } - // 7.2.3 IsCallable(argument) - // https://tc39.github.io/ecma262/#sec-iscallable - function IsCallable(argument) { - // NOTE: This is an approximation as we cannot check for [[Call]] internal method. - return typeof argument === "function"; - } - // 7.2.4 IsConstructor(argument) - // https://tc39.github.io/ecma262/#sec-isconstructor - function IsConstructor(argument) { - // NOTE: This is an approximation as we cannot check for [[Construct]] internal method. - return typeof argument === "function"; - } - // 7.2.7 IsPropertyKey(argument) - // https://tc39.github.io/ecma262/#sec-ispropertykey - function IsPropertyKey(argument) { - switch (Type(argument)) { - case 3 /* String */: return true; - case 4 /* Symbol */: return true; - default: return false; - } + }); + } + /** + * 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 = undefined; } - // 7.3 Operations on Objects - // https://tc39.github.io/ecma262/#sec-operations-on-objects - // 7.3.9 GetMethod(V, P) - // https://tc39.github.io/ecma262/#sec-getmethod - function GetMethod(V, P) { - var func = V[P]; - if (func === undefined || func === null) - return undefined; - if (!IsCallable(func)) - throw new TypeError(); - return func; - } - // 7.4 Operations on Iterator Objects - // https://tc39.github.io/ecma262/#sec-operations-on-iterator-objects - function GetIterator(obj) { - var method = GetMethod(obj, iteratorSymbol); - if (!IsCallable(method)) - throw new TypeError(); // from Call - var iterator = method.call(obj); - if (!IsObject(iterator)) - throw new TypeError(); - return iterator; - } - // 7.4.4 IteratorValue(iterResult) - // https://tc39.github.io/ecma262/2016/#sec-iteratorvalue - function IteratorValue(iterResult) { - return iterResult.value; - } - // 7.4.5 IteratorStep(iterator) - // https://tc39.github.io/ecma262/#sec-iteratorstep - function IteratorStep(iterator) { - var result = iterator.next(); - return result.done ? false : result; - } - // 7.4.6 IteratorClose(iterator, completion) - // https://tc39.github.io/ecma262/#sec-iteratorclose - function IteratorClose(iterator) { - var f = iterator["return"]; - if (f) - f.call(iterator); - } - // 9.1 Ordinary Object Internal Methods and Internal Slots - // https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots - // 9.1.1.1 OrdinaryGetPrototypeOf(O) - // https://tc39.github.io/ecma262/#sec-ordinarygetprototypeof - function OrdinaryGetPrototypeOf(O) { - var proto = Object.getPrototypeOf(O); - if (typeof O !== "function" || O === functionPrototype) - return proto; - // TypeScript doesn't set __proto__ in ES5, as it's non-standard. - // Try to determine the superclass constructor. Compatible implementations - // must either set __proto__ on a subclass constructor to the superclass constructor, - // or ensure each class has a valid `constructor` property on its prototype that - // points back to the constructor. - // If this is not the same as Function.[[Prototype]], then this is definately inherited. - // This is the case when in ES6 or when using __proto__ in a compatible browser. - if (proto !== functionPrototype) - return proto; - // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage. - var prototype = O.prototype; - var prototypeProto = prototype && Object.getPrototypeOf(prototype); - if (prototypeProto == null || prototypeProto === Object.prototype) - return proto; - // If the constructor was not a function, then we cannot determine the heritage. - var constructor = prototypeProto.constructor; - if (typeof constructor !== "function") - return proto; - // If we have some kind of self-reference, then we cannot determine the heritage. - if (constructor === O) - return proto; - // we have a pretty good guess at the heritage. - return constructor; - } - // naive Map shim - function CreateMapPolyfill() { - var cacheSentinel = {}; - var arraySentinel = []; - var MapIterator = /** @class */ (function () { - function MapIterator(keys, values, selector) { - this._index = 0; - this._keys = keys; - this._values = values; - this._selector = selector; - } - MapIterator.prototype["@@iterator"] = function () { return this; }; - MapIterator.prototype[iteratorSymbol] = function () { return this; }; - MapIterator.prototype.next = function () { - var index = this._index; - if (index >= 0 && index < this._keys.length) { - var result = this._selector(this._keys[index], this._values[index]); - if (index + 1 >= this._keys.length) { - this._index = -1; - this._keys = arraySentinel; - this._values = arraySentinel; - } - else { - this._index++; - } - return { value: result, done: false }; - } - return { value: undefined, done: true }; - }; - MapIterator.prototype.throw = function (error) { - if (this._index >= 0) { - this._index = -1; - this._keys = arraySentinel; - this._values = arraySentinel; - } - throw error; - }; - MapIterator.prototype.return = function (value) { - if (this._index >= 0) { - this._index = -1; - this._keys = arraySentinel; - this._values = arraySentinel; - } - return { value: value, done: true }; - }; - return MapIterator; - }()); - return /** @class */ (function () { - function Map() { - this._keys = []; - this._values = []; - this._cacheKey = cacheSentinel; - this._cacheIndex = -2; - } - Object.defineProperty(Map.prototype, "size", { - get: function () { return this._keys.length; }, - enumerable: true, - configurable: true - }); - Map.prototype.has = function (key) { return this._find(key, /*insert*/ false) >= 0; }; - Map.prototype.get = function (key) { - var index = this._find(key, /*insert*/ false); - return index >= 0 ? this._values[index] : undefined; - }; - Map.prototype.set = function (key, value) { - var index = this._find(key, /*insert*/ true); - this._values[index] = value; - return this; - }; - Map.prototype.delete = function (key) { - var index = this._find(key, /*insert*/ false); - if (index >= 0) { - var size = this._keys.length; - for (var i = index + 1; i < size; i++) { - this._keys[i - 1] = this._keys[i]; - this._values[i - 1] = this._values[i]; - } - this._keys.length--; - this._values.length--; - if (key === this._cacheKey) { - this._cacheKey = cacheSentinel; - this._cacheIndex = -2; - } - return true; - } - return false; - }; - Map.prototype.clear = function () { - this._keys.length = 0; - this._values.length = 0; - this._cacheKey = cacheSentinel; - this._cacheIndex = -2; - }; - Map.prototype.keys = function () { return new MapIterator(this._keys, this._values, getKey); }; - Map.prototype.values = function () { return new MapIterator(this._keys, this._values, getValue); }; - Map.prototype.entries = function () { return new MapIterator(this._keys, this._values, getEntry); }; - Map.prototype["@@iterator"] = function () { return this.entries(); }; - Map.prototype[iteratorSymbol] = function () { return this.entries(); }; - Map.prototype._find = function (key, insert) { - if (this._cacheKey !== key) { - this._cacheIndex = this._keys.indexOf(this._cacheKey = key); - } - if (this._cacheIndex < 0 && insert) { - this._cacheIndex = this._keys.length; - this._keys.push(key); - this._values.push(undefined); - } - return this._cacheIndex; - }; - return Map; - }()); - function getKey(key, _) { - return key; - } - function getValue(_, value) { - return value; - } - function getEntry(key, value) { - return [key, value]; - } + const include = []; + if (options.includeDeleted) { + include.push("deleted"); } - // naive Set shim - function CreateSetPolyfill() { - return /** @class */ (function () { - function Set() { - this._map = new _Map(); - } - Object.defineProperty(Set.prototype, "size", { - get: function () { return this._map.size; }, - enumerable: true, - configurable: true - }); - Set.prototype.has = function (value) { return this._map.has(value); }; - Set.prototype.add = function (value) { return this._map.set(value, value), this; }; - Set.prototype.delete = function (value) { return this._map.delete(value); }; - Set.prototype.clear = function () { this._map.clear(); }; - Set.prototype.keys = function () { return this._map.keys(); }; - Set.prototype.values = function () { return this._map.values(); }; - Set.prototype.entries = function () { return this._map.entries(); }; - Set.prototype["@@iterator"] = function () { return this.keys(); }; - Set.prototype[iteratorSymbol] = function () { return this.keys(); }; - return Set; - }()); - } - // naive WeakMap shim - function CreateWeakMapPolyfill() { - var UUID_SIZE = 16; - var keys = HashMap.create(); - var rootKey = CreateUniqueKey(); - return /** @class */ (function () { - function WeakMap() { - this._key = CreateUniqueKey(); - } - WeakMap.prototype.has = function (target) { - var table = GetOrCreateWeakMapTable(target, /*create*/ false); - return table !== undefined ? HashMap.has(table, this._key) : false; - }; - WeakMap.prototype.get = function (target) { - var table = GetOrCreateWeakMapTable(target, /*create*/ false); - return table !== undefined ? HashMap.get(table, this._key) : undefined; - }; - WeakMap.prototype.set = function (target, value) { - var table = GetOrCreateWeakMapTable(target, /*create*/ true); - table[this._key] = value; - return this; - }; - WeakMap.prototype.delete = function (target) { - var table = GetOrCreateWeakMapTable(target, /*create*/ false); - return table !== undefined ? delete table[this._key] : false; - }; - WeakMap.prototype.clear = function () { - // NOTE: not a real clear, just makes the previous data unreachable - this._key = CreateUniqueKey(); - }; - return WeakMap; - }()); - function CreateUniqueKey() { - var key; - do - key = "@@WeakMap@@" + CreateUUID(); - while (HashMap.has(keys, key)); - keys[key] = true; - return key; - } - function GetOrCreateWeakMapTable(target, create) { - if (!hasOwn.call(target, rootKey)) { - if (!create) - return undefined; - Object.defineProperty(target, rootKey, { value: HashMap.create() }); - } - return target[rootKey]; - } - function FillRandomBytes(buffer, size) { - for (var i = 0; i < size; ++i) - buffer[i] = Math.random() * 0xff | 0; - return buffer; - } - function GenRandomBytes(size) { - if (typeof Uint8Array === "function") { - if (typeof crypto !== "undefined") - return crypto.getRandomValues(new Uint8Array(size)); - if (typeof msCrypto !== "undefined") - return msCrypto.getRandomValues(new Uint8Array(size)); - return FillRandomBytes(new Uint8Array(size), size); - } - return FillRandomBytes(new Array(size), size); - } - function CreateUUID() { - var data = GenRandomBytes(UUID_SIZE); - // mark as random - RFC 4122 § 4.4 - data[6] = data[6] & 0x4f | 0x40; - data[8] = data[8] & 0xbf | 0x80; - var result = ""; - for (var offset = 0; offset < UUID_SIZE; ++offset) { - var byte = data[offset]; - if (offset === 4 || offset === 6 || offset === 8) - result += "-"; - if (byte < 16) - result += "0"; - result += byte.toString(16).toLowerCase(); - } - return result; - } + if (options.includeMetadata) { + include.push("metadata"); } - // uses a heuristic used by v8 and chakra to force an object into dictionary mode. - function MakeDictionary(obj) { - obj.__ = undefined; - delete obj.__; - return obj; + if (options.includeSystem) { + include.push("system"); } - }); -})(Reflect || (Reflect = {})); - - -/***/ }), - -/***/ 48699: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright 2010-2012 Mikeal Rogers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - - -var extend = __nccwpck_require__(38171) -var cookies = __nccwpck_require__(50976) -var helpers = __nccwpck_require__(74845) - -var paramsHaveRequestBody = helpers.paramsHaveRequestBody - -// organize params for patch, post, put, head, del -function initParams (uri, options, callback) { - if (typeof options === 'function') { - callback = options - } - - var params = {} - if (options !== null && typeof options === 'object') { - extend(params, options, {uri: uri}) - } else if (typeof uri === 'string') { - extend(params, {uri: uri}) - } else { - extend(params, uri) - } - - params.callback = callback || params.callback - return params -} - -function request (uri, options, callback) { - if (typeof uri === 'undefined') { - throw new Error('undefined is not a valid uri or options object.') - } - - var params = initParams(uri, options, callback) - - if (params.method === 'HEAD' && paramsHaveRequestBody(params)) { - throw new Error('HTTP HEAD requests MUST NOT include a request body.') - } - - return new request.Request(params) -} - -function verbFunc (verb) { - var method = verb.toUpperCase() - return function (uri, options, callback) { - var params = initParams(uri, options, callback) - params.method = method - return request(params, params.callback) - } -} - -// define like this to please codeintel/intellisense IDEs -request.get = verbFunc('get') -request.head = verbFunc('head') -request.options = verbFunc('options') -request.post = verbFunc('post') -request.put = verbFunc('put') -request.patch = verbFunc('patch') -request.del = verbFunc('delete') -request['delete'] = verbFunc('delete') - -request.jar = function (store) { - return cookies.jar(store) -} - -request.cookie = function (str) { - return cookies.parse(str) -} - -function wrapRequestMethod (method, options, requester, verb) { - return function (uri, opts, callback) { - var params = initParams(uri, opts, callback) - - var target = {} - extend(true, target, options, params) - - target.pool = params.pool || options.pool - - if (verb) { - target.method = verb.toUpperCase() - } - - if (typeof requester === 'function') { - method = requester + // AsyncIterableIterator to iterate over containers + const listSegmentOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include } : {})); + 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)); + }, + }; } - - return method(target, target.callback) - } -} - -request.defaults = function (options, requester) { - var self = this - - options = options || {} - - if (typeof options === 'function') { - requester = options - options = {} - } - - var defaults = wrapRequestMethod(self, options, requester) - - var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete'] - verbs.forEach(function (verb) { - defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb) - }) - - defaults.cookie = wrapRequestMethod(self.cookie, options, requester) - defaults.jar = self.jar - defaults.defaults = self.defaults - return defaults -} - -request.forever = function (agentOptions, optionsArg) { - var options = {} - if (optionsArg) { - extend(options, optionsArg) - } - if (agentOptions) { - options.agentOptions = agentOptions - } - - options.forever = true - return request.defaults(options) -} - -// Exports - -module.exports = request -request.Request = __nccwpck_require__(70304) -request.initParams = initParams - -// Backwards compatibility for request.debug -Object.defineProperty(request, 'debug', { - enumerable: true, - get: function () { - return request.Request.debug - }, - set: function (debug) { - request.Request.debug = debug - } -}) - - -/***/ }), - -/***/ 76996: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var caseless = __nccwpck_require__(35684) -var uuid = __nccwpck_require__(71435) -var helpers = __nccwpck_require__(74845) - -var md5 = helpers.md5 -var toBase64 = helpers.toBase64 - -function Auth (request) { - // define all public properties here - this.request = request - this.hasAuth = false - this.sentAuth = false - this.bearerToken = null - this.user = null - this.pass = null -} - -Auth.prototype.basic = function (user, pass, sendImmediately) { - var self = this - if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) { - self.request.emit('error', new Error('auth() received invalid user or password')) - } - self.user = user - self.pass = pass - self.hasAuth = true - var header = user + ':' + (pass || '') - if (sendImmediately || typeof sendImmediately === 'undefined') { - var authHeader = 'Basic ' + toBase64(header) - self.sentAuth = true - return authHeader - } -} - -Auth.prototype.bearer = function (bearer, sendImmediately) { - var self = this - self.bearerToken = bearer - self.hasAuth = true - if (sendImmediately || typeof sendImmediately === 'undefined') { - if (typeof bearer === 'function') { - bearer = bearer() + /** + * 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, expiresOn, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getUserDelegationKey", options); + try { + const response = await this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn, false), + }, Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + 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; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message, + }); + throw e; + } + finally { + span.end(); + } } - var authHeader = 'Bearer ' + (bearer || '') - self.sentAuth = true - return authHeader - } -} - -Auth.prototype.digest = function (method, path, authHeader) { - // TODO: More complete implementation of RFC 2617. - // - handle challenge.domain - // - support qop="auth-int" only - // - handle Authentication-Info (not necessarily?) - // - check challenge.stale (not necessarily?) - // - increase nc (not necessarily?) - // For reference: - // http://tools.ietf.org/html/rfc2617#section-3 - // https://github.com/bagder/curl/blob/master/lib/http_digest.c - - var self = this - - var challenge = {} - var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi - while (true) { - var match = re.exec(authHeader) - if (!match) { - break + /** + * 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); } - challenge[match[1]] = match[2] || match[3] - } - - /** - * RFC 2617: handle both MD5 and MD5-sess algorithms. - * - * If the algorithm directive's value is "MD5" or unspecified, then HA1 is - * HA1=MD5(username:realm:password) - * If the algorithm directive's value is "MD5-sess", then HA1 is - * HA1=MD5(MD5(username:realm:password):nonce:cnonce) - */ - var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) { - var ha1 = md5(user + ':' + realm + ':' + pass) - if (algorithm && algorithm.toLowerCase() === 'md5-sess') { - return md5(ha1 + ':' + nonce + ':' + cnonce) - } else { - return ha1 - } - } - - var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth' - var nc = qop && '00000001' - var cnonce = qop && uuid().replace(/-/g, '') - var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce) - var ha2 = md5(method + ':' + path) - var digestResponse = qop - ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) - : md5(ha1 + ':' + challenge.nonce + ':' + ha2) - var authValues = { - username: self.user, - realm: challenge.realm, - nonce: challenge.nonce, - uri: path, - qop: qop, - response: digestResponse, - nc: nc, - cnonce: cnonce, - algorithm: challenge.algorithm, - opaque: challenge.opaque - } - - authHeader = [] - for (var k in authValues) { - if (authValues[k]) { - if (k === 'qop' || k === 'nc' || k === 'algorithm') { - authHeader.push(k + '=' + authValues[k]) - } else { - authHeader.push(k + '="' + authValues[k] + '"') - } + /** + * 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(expiresOn, 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 (expiresOn === undefined) { + const now = new Date(); + expiresOn = new Date(now.getTime() + 3600 * 1000); + } + const sas = generateAccountSASQueryParameters(Object.assign({ permissions, + expiresOn, + resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); + return appendToURLQuery(this.url, sas); } - } - authHeader = 'Digest ' + authHeader.join(', ') - self.sentAuth = true - return authHeader -} - -Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) { - var self = this - var request = self.request - - var authHeader - if (bearer === undefined && user === undefined) { - self.request.emit('error', new Error('no auth mechanism defined')) - } else if (bearer !== undefined) { - authHeader = self.bearer(bearer, sendImmediately) - } else { - authHeader = self.basic(user, pass, sendImmediately) - } - if (authHeader) { - request.setHeader('authorization', authHeader) - } -} - -Auth.prototype.onResponse = function (response) { - var self = this - var request = self.request - - if (!self.hasAuth || self.sentAuth) { return null } - - var c = caseless(response.headers) - - var authHeader = c.get('www-authenticate') - var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase() - request.debug('reauth', authVerb) - - switch (authVerb) { - case 'basic': - return self.basic(self.user, self.pass, true) - - case 'bearer': - return self.bearer(self.bearerToken, true) - - case 'digest': - return self.digest(request.method, request.path, authHeader) - } -} - -exports.g = Auth - - -/***/ }), - -/***/ 50976: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var tough = __nccwpck_require__(47372) - -var Cookie = tough.Cookie -var CookieJar = tough.CookieJar - -exports.parse = function (str) { - if (str && str.uri) { - str = str.uri - } - if (typeof str !== 'string') { - throw new Error('The cookie function only accepts STRING as param') - } - return Cookie.parse(str, {loose: true}) } -// Adapt the sometimes-Async api of tough.CookieJar to our requirements -function RequestJar (store) { - var self = this - self._jar = new CookieJar(store, {looseMode: true}) -} -RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) { - var self = this - return self._jar.setCookieSync(cookieOrStr, uri, options || {}) -} -RequestJar.prototype.getCookieString = function (uri) { - var self = this - return self._jar.getCookieStringSync(uri) -} -RequestJar.prototype.getCookies = function (uri) { - var self = this - return self._jar.getCookiesSync(uri) -} +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** Known values of {@link EncryptionAlgorithmType} that the service accepts. */ +exports.KnownEncryptionAlgorithmType = void 0; +(function (KnownEncryptionAlgorithmType) { + KnownEncryptionAlgorithmType["AES256"] = "AES256"; +})(exports.KnownEncryptionAlgorithmType || (exports.KnownEncryptionAlgorithmType = {})); -exports.jar = function (store) { - return new RequestJar(store) -} +Object.defineProperty(exports, "BaseRequestPolicy", ({ + enumerable: true, + get: function () { return coreHttp.BaseRequestPolicy; } +})); +Object.defineProperty(exports, "HttpHeaders", ({ + enumerable: true, + get: function () { return coreHttp.HttpHeaders; } +})); +Object.defineProperty(exports, "RequestPolicyOptions", ({ + enumerable: true, + get: function () { return coreHttp.RequestPolicyOptions; } +})); +Object.defineProperty(exports, "RestError", ({ + enumerable: true, + get: function () { return coreHttp.RestError; } +})); +Object.defineProperty(exports, "WebResource", ({ + enumerable: true, + get: function () { return coreHttp.WebResource; } +})); +Object.defineProperty(exports, "deserializationPolicy", ({ + enumerable: true, + get: function () { return coreHttp.deserializationPolicy; } +})); +exports.AccountSASPermissions = AccountSASPermissions; +exports.AccountSASResourceTypes = AccountSASResourceTypes; +exports.AccountSASServices = AccountSASServices; +exports.AnonymousCredential = AnonymousCredential; +exports.AnonymousCredentialPolicy = AnonymousCredentialPolicy; +exports.AppendBlobClient = AppendBlobClient; +exports.BlobBatch = BlobBatch; +exports.BlobBatchClient = BlobBatchClient; +exports.BlobClient = BlobClient; +exports.BlobLeaseClient = BlobLeaseClient; +exports.BlobSASPermissions = BlobSASPermissions; +exports.BlobServiceClient = BlobServiceClient; +exports.BlockBlobClient = BlockBlobClient; +exports.ContainerClient = ContainerClient; +exports.ContainerSASPermissions = ContainerSASPermissions; +exports.Credential = Credential; +exports.CredentialPolicy = CredentialPolicy; +exports.PageBlobClient = PageBlobClient; +exports.Pipeline = Pipeline; +exports.SASQueryParameters = SASQueryParameters; +exports.StorageBrowserPolicy = StorageBrowserPolicy; +exports.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; +exports.StorageOAuthScopes = StorageOAuthScopes; +exports.StorageRetryPolicy = StorageRetryPolicy; +exports.StorageRetryPolicyFactory = StorageRetryPolicyFactory; +exports.StorageSharedKeyCredential = StorageSharedKeyCredential; +exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; +exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters; +exports.generateBlobSASQueryParameters = generateBlobSASQueryParameters; +exports.isPipelineLike = isPipelineLike; +exports.logger = logger; +exports.newPipeline = newPipeline; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 75654: -/***/ ((module) => { +/***/ 2856: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -function formatHostname (hostname) { - // canonicalize the hostname, so that 'oogle.com' won't match 'google.com' - return hostname.replace(/^\.*/, '.').toLowerCase() -} - -function parseNoProxyZone (zone) { - zone = zone.trim().toLowerCase() - - var zoneParts = zone.split(':', 2) - var zoneHost = formatHostname(zoneParts[0]) - var zonePort = zoneParts[1] - var hasPort = zone.indexOf(':') > -1 - - return {hostname: zoneHost, port: zonePort, hasPort: hasPort} -} +const WritableStream = (__nccwpck_require__(84492).Writable) +const inherits = (__nccwpck_require__(47261).inherits) -function uriInNoProxy (uri, noProxy) { - var port = uri.port || (uri.protocol === 'https:' ? '443' : '80') - var hostname = formatHostname(uri.hostname) - var noProxyList = noProxy.split(',') +const StreamSearch = __nccwpck_require__(88534) - // iterate through the noProxyList until it finds a match. - return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) { - var isMatchedAt = hostname.indexOf(noProxyZone.hostname) - var hostnameMatched = ( - isMatchedAt > -1 && - (isMatchedAt === hostname.length - noProxyZone.hostname.length) - ) +const PartStream = __nccwpck_require__(38710) +const HeaderParser = __nccwpck_require__(90333) - if (noProxyZone.hasPort) { - return (port === noProxyZone.port) && hostnameMatched - } +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} - return hostnameMatched - }) -} +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) -function getProxyFromURI (uri) { - // Decide the proper request proxy to use based on the request URI object and the - // environmental variables (NO_PROXY, HTTP_PROXY, etc.) - // respect NO_PROXY environment variables (see: https://lynx.invisible-island.net/lynx2.8.7/breakout/lynx_help/keystrokes/environments.html) + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - var noProxy = process.env.NO_PROXY || process.env.no_proxy || '' + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - // if the noProxy is a wildcard then return null + this._headerFirst = cfg.headerFirst - if (noProxy === '*') { - return null - } + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false - // if the noProxy is not empty and the uri is found return null + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) +} +inherits(Dicer, WritableStream) - if (noProxy !== '' && uriInNoProxy(uri, noProxy)) { - return null - } +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return + } + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + } + } else { WritableStream.prototype.emit.apply(this, arguments) } +} - // Check for HTTP or HTTPS Proxy in environment Else default to null +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } - if (uri.protocol === 'http:') { - return process.env.HTTP_PROXY || - process.env.http_proxy || null + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this._events.preamble) { this.emit('preamble', this._part) } else { this._ignore() } + } + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } } - if (uri.protocol === 'https:') { - return process.env.HTTPS_PROXY || - process.env.https_proxy || - process.env.HTTP_PROXY || - process.env.http_proxy || null + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false } - // if none of that works, return null - // (What uri protocol are you using then?) + this._bparser.push(data) - return null + if (this._pause) { this._cb = cb } else { cb() } } -module.exports = getProxyFromURI - - -/***/ }), - -/***/ 3248: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var fs = __nccwpck_require__(57147) -var qs = __nccwpck_require__(63477) -var validate = __nccwpck_require__(75697) -var extend = __nccwpck_require__(38171) - -function Har (request) { - this.request = request +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined } -Har.prototype.reducer = function (obj, pair) { - // new property ? - if (obj[pair.name] === undefined) { - obj[pair.name] = pair.value - return obj - } - - // existing? convert to array - var arr = [ - obj[pair.name], - pair.value - ] - - obj[pair.name] = arr - - return obj +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) } -Har.prototype.prep = function (data) { - // construct utility properties - data.queryObj = {} - data.headersObj = {} - data.postData.jsonObj = false - data.postData.paramsObj = false - - // construct query objects - if (data.queryString && data.queryString.length) { - data.queryObj = data.queryString.reduce(this.reducer, {}) - } - - // construct headers objects - if (data.headers && data.headers.length) { - // loweCase header keys - data.headersObj = data.headers.reduceRight(function (headers, header) { - headers[header.name] = header.value - return headers - }, {}) - } - - // construct Cookie header - if (data.cookies && data.cookies.length) { - var cookies = data.cookies.map(function (cookie) { - return cookie.name + '=' + cookie.value - }) - - if (cookies.length) { - data.headersObj.cookie = cookies.join('; ') - } - } - - // prep body - function some (arr) { - return arr.some(function (type) { - return data.postData.mimeType.indexOf(type) === 0 - }) +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() } +} - if (some([ - 'multipart/mixed', - 'multipart/related', - 'multipart/form-data', - 'multipart/alternative'])) { - // reset values - data.postData.mimeType = 'multipart/form-data' - } else if (some([ - 'application/x-www-form-urlencoded'])) { - if (!data.postData.params) { - data.postData.text = '' - } else { - data.postData.paramsObj = data.postData.params.reduce(this.reducer, {}) +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true - // always overwrite - data.postData.text = qs.stringify(data.postData.paramsObj) + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } } - } else if (some([ - 'text/json', - 'text/x-json', - 'application/json', - 'application/x-json'])) { - data.postData.mimeType = 'application/json' - - if (data.postData.text) { - try { - data.postData.jsonObj = JSON.parse(data.postData.text) - } catch (e) { - this.request.debug(e) - - // force back to text/plain - data.postData.mimeType = 'text/plain' + if (this._dashes === 2) { + if ((start + i) < end && this._events.trailer) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false } } + if (this._dashes) { return } } - - return data -} - -Har.prototype.options = function (options) { - // skip if no har property defined - if (!options.har) { - return options - } - - var har = {} - extend(har, options.har) - - // only process the first entry - if (har.log && har.log.entries) { - har = har.log.entries[0] - } - - // add optional properties to make validation successful - har.url = har.url || options.url || options.uri || options.baseUrl || '/' - har.httpVersion = har.httpVersion || 'HTTP/1.1' - har.queryString = har.queryString || [] - har.headers = har.headers || [] - har.cookies = har.cookies || [] - har.postData = har.postData || {} - har.postData.mimeType = har.postData.mimeType || 'application/octet-stream' - - har.bodySize = 0 - har.headersSize = 0 - har.postData.size = 0 - - if (!validate.request(har)) { - return options - } - - // clean up and get some utility properties - var req = this.prep(har) - - // construct new options - if (req.url) { - options.url = req.url - } - - if (req.method) { - options.method = req.method - } - - if (Object.keys(req.queryObj).length) { - options.qs = req.queryObj - } - - if (Object.keys(req.headersObj).length) { - options.headers = req.headersObj - } - - function test (type) { - return req.postData.mimeType.indexOf(type) === 0 + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() + } + if (this._isPreamble && this._events.preamble) { this.emit('preamble', this._part) } else if (this._isPreamble !== true && this._events.part) { this.emit('part', this._part) } else { this._ignore() } + if (!this._isPreamble) { this._inHeader = true } } - if (test('application/x-www-form-urlencoded')) { - options.form = req.postData.paramsObj - } else if (test('application/json')) { - if (req.postData.jsonObj) { - options.body = req.postData.jsonObj - options.json = true + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } } - } else if (test('multipart/form-data')) { - options.formData = {} - - req.postData.params.forEach(function (param) { - var attachment = {} - - if (!param.fileName && !param.contentType) { - options.formData[param.name] = param.value - return - } - - // attempt to read from disk! - if (param.fileName && !param.value) { - attachment.value = fs.createReadStream(param.fileName) - } else if (param.value) { - attachment.value = param.value - } - - if (param.fileName) { - attachment.options = { - filename: param.fileName, - contentType: param.contentType ? param.contentType : null - } + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() + } + } + }) } - - options.formData[param.name] = attachment - }) - } else { - if (req.postData.text) { - options.body = req.postData.text } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 } - - return options -} - -exports.t = Har - - -/***/ }), - -/***/ 34473: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var crypto = __nccwpck_require__(6113) - -function randomString (size) { - var bits = (size + 1) * 6 - var buffer = crypto.randomBytes(Math.ceil(bits / 8)) - var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '') - return string.slice(0, size) } -function calculatePayloadHash (payload, algorithm, contentType) { - var hash = crypto.createHash(algorithm) - hash.update('hawk.1.payload\n') - hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n') - hash.update(payload || '') - hash.update('\n') - return hash.digest('base64') -} - -exports.calculateMac = function (credentials, opts) { - var normalized = 'hawk.1.header\n' + - opts.ts + '\n' + - opts.nonce + '\n' + - (opts.method || '').toUpperCase() + '\n' + - opts.resource + '\n' + - opts.host.toLowerCase() + '\n' + - opts.port + '\n' + - (opts.hash || '') + '\n' - - if (opts.ext) { - normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n') - } - - normalized = normalized + '\n' +Dicer.prototype._unpause = function () { + if (!this._pause) { return } - if (opts.app) { - normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n' + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() } - - var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized) - var digest = hmac.digest('base64') - return digest } -exports.header = function (uri, method, opts) { - var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000) - var credentials = opts.credentials - if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) { - return '' - } - - if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) { - return '' - } - - var artifacts = { - ts: timestamp, - nonce: opts.nonce || randomString(6), - method: method, - resource: uri.pathname + (uri.search || ''), - host: uri.hostname, - port: uri.port || (uri.protocol === 'http:' ? 80 : 443), - hash: opts.hash, - ext: opts.ext, - app: opts.app, - dlg: opts.dlg - } - - if (!artifacts.hash && (opts.payload || opts.payload === '')) { - artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType) - } - - var mac = exports.calculateMac(credentials, artifacts) - - var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== '' - var header = 'Hawk id="' + credentials.id + - '", ts="' + artifacts.ts + - '", nonce="' + artifacts.nonce + - (artifacts.hash ? '", hash="' + artifacts.hash : '') + - (hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') + - '", mac="' + mac + '"' - - if (artifacts.app) { - header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"' - } - - return header -} +module.exports = Dicer /***/ }), -/***/ 74845: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 90333: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var jsonSafeStringify = __nccwpck_require__(57073) -var crypto = __nccwpck_require__(6113) -var Buffer = (__nccwpck_require__(21867).Buffer) - -var defer = typeof setImmediate === 'undefined' - ? process.nextTick - : setImmediate - -function paramsHaveRequestBody (params) { - return ( - params.body || - params.requestBodyStream || - (params.json && typeof params.json !== 'boolean') || - params.multipart - ) -} +const EventEmitter = (__nccwpck_require__(15673).EventEmitter) +const inherits = (__nccwpck_require__(47261).inherits) +const getLimit = __nccwpck_require__(49692) -function safeStringify (obj, replacer) { - var ret - try { - ret = JSON.stringify(obj, replacer) - } catch (e) { - ret = jsonSafeStringify(obj, replacer) - } - return ret -} +const StreamSearch = __nccwpck_require__(88534) -function md5 (str) { - return crypto.createHash('md5').update(str).digest('hex') -} +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex -function isReadStream (rs) { - return rs.readable && rs.path && rs.mode -} +function HeaderParser (cfg) { + EventEmitter.call(this) -function toBase64 (str) { - return Buffer.from(str || '', 'utf8').toString('base64') -} + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } -function copy (obj) { - var o = {} - Object.keys(obj).forEach(function (i) { - o[i] = obj[i] + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } }) - return o } +inherits(HeaderParser, EventEmitter) -function version () { - var numbers = process.version.replace('v', '').split('.') - return { - major: parseInt(numbers[0], 10), - minor: parseInt(numbers[1], 10), - patch: parseInt(numbers[2], 10) - } +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } } -exports.paramsHaveRequestBody = paramsHaveRequestBody -exports.safeStringify = safeStringify -exports.md5 = md5 -exports.isReadStream = isReadStream -exports.toBase64 = toBase64 -exports.copy = copy -exports.version = version -exports.defer = defer - - -/***/ }), - -/***/ 87810: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var uuid = __nccwpck_require__(71435) -var CombinedStream = __nccwpck_require__(85443) -var isstream = __nccwpck_require__(83362) -var Buffer = (__nccwpck_require__(21867).Buffer) - -function Multipart (request) { - this.request = request - this.boundary = uuid() - this.chunked = false - this.body = null +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() } -Multipart.prototype.isChunked = function (options) { - var self = this - var chunked = false - var parts = options.data || options - - if (!parts.forEach) { - self.request.emit('error', new Error('Argument error, options.multipart.')) - } - - if (options.chunked !== undefined) { - chunked = options.chunked - } - - if (self.request.getHeader('transfer-encoding') === 'chunked') { - chunked = true - } - - if (!chunked) { - parts.forEach(function (part) { - if (typeof part.body === 'undefined') { - self.request.emit('error', new Error('Body attribute missing in multipart.')) - } - if (isstream(part.body)) { - chunked = true - } - }) - } - - return chunked +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) } -Multipart.prototype.setHeaders = function (chunked) { - var self = this - - if (chunked && !self.request.hasHeader('transfer-encoding')) { - self.request.setHeader('transfer-encoding', 'chunked') - } +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } - var header = self.request.getHeader('content-type') + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h - if (!header || header.indexOf('multipart') === -1) { - self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary) - } else { - if (header.indexOf('boundary') !== -1) { - self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1') - } else { - self.request.setHeader('content-type', header + '; boundary=' + self.boundary) + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } } - } -} - -Multipart.prototype.build = function (parts, chunked) { - var self = this - var body = chunked ? new CombinedStream() : [] - function add (part) { - if (typeof part === 'number') { - part = part.toString() + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return } - return chunked ? body.append(part) : body.push(Buffer.from(part)) - } - - if (self.request.preambleCRLF) { - add('\r\n') - } - - parts.forEach(function (part) { - var preamble = '--' + self.boundary + '\r\n' - Object.keys(part).forEach(function (key) { - if (key === 'body') { return } - preamble += key + ': ' + part[key] + '\r\n' - }) - preamble += '\r\n' - add(preamble) - add(part.body) - add('\r\n') - }) - add('--' + self.boundary + '--') - - if (self.request.postambleCRLF) { - add('\r\n') + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } } - - return body -} - -Multipart.prototype.onRequest = function (options) { - var self = this - - var chunked = self.isChunked(options) - var parts = options.data || options - - self.setHeaders(chunked) - self.chunked = chunked - self.body = self.build(parts, chunked) } -exports.$ = Multipart +module.exports = HeaderParser /***/ }), -/***/ 41174: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 38710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var url = __nccwpck_require__(57310) -var qs = __nccwpck_require__(22760) -var caseless = __nccwpck_require__(35684) -var uuid = __nccwpck_require__(71435) -var oauth = __nccwpck_require__(43248) -var crypto = __nccwpck_require__(6113) -var Buffer = (__nccwpck_require__(21867).Buffer) +const inherits = (__nccwpck_require__(47261).inherits) +const ReadableStream = (__nccwpck_require__(84492).Readable) -function OAuth (request) { - this.request = request - this.params = null +function PartStream (opts) { + ReadableStream.call(this, opts) } +inherits(PartStream, ReadableStream) -OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) { - var oa = {} - for (var i in _oauth) { - oa['oauth_' + i] = _oauth[i] - } - if (!oa.oauth_version) { - oa.oauth_version = '1.0' - } - if (!oa.oauth_timestamp) { - oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString() - } - if (!oa.oauth_nonce) { - oa.oauth_nonce = uuid().replace(/-/g, '') - } - if (!oa.oauth_signature_method) { - oa.oauth_signature_method = 'HMAC-SHA1' - } +PartStream.prototype._read = function (n) {} - var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase - delete oa.oauth_consumer_secret - delete oa.oauth_private_key +module.exports = PartStream - var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase - delete oa.oauth_token_secret - var realm = oa.oauth_realm - delete oa.oauth_realm - delete oa.oauth_transport_method +/***/ }), - var baseurl = uri.protocol + '//' + uri.host + uri.pathname - var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&')) +/***/ 88534: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - oa.oauth_signature = oauth.sign( - oa.oauth_signature_method, - method, - baseurl, - params, - consumer_secret_or_private_key, // eslint-disable-line camelcase - token_secret // eslint-disable-line camelcase - ) +"use strict"; - if (realm) { - oa.realm = realm - } - return oa -} +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ +const EventEmitter = (__nccwpck_require__(15673).EventEmitter) +const inherits = (__nccwpck_require__(47261).inherits) -OAuth.prototype.buildBodyHash = function (_oauth, body) { - if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) { - this.request.emit('error', new Error('oauth: ' + _oauth.signature_method + - ' signature_method not supported with body_hash signing.')) +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) } - var shasum = crypto.createHash('sha1') - shasum.update(body || '') - var sha1 = shasum.digest('hex') - - return Buffer.from(sha1, 'hex').toString('base64') -} - -OAuth.prototype.concatParams = function (oa, sep, wrap) { - wrap = wrap || '' - - var params = Object.keys(oa).filter(function (i) { - return i !== 'realm' && i !== 'oauth_signature' - }).sort() - - if (oa.realm) { - params.splice(0, 0, 'realm') + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') } - params.push('oauth_signature') - - return params.map(function (i) { - return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap - }).join(sep) -} - -OAuth.prototype.onRequest = function (_oauth) { - var self = this - self.params = _oauth - - var uri = self.request.uri || {} - var method = self.request.method || '' - var headers = caseless(self.request.headers) - var body = self.request.body || '' - var qsLib = self.request.qsLib || qs - var form - var query - var contentType = headers.get('content-type') || '' - var formContentType = 'application/x-www-form-urlencoded' - var transport = _oauth.transport_method || 'header' + const needleLength = needle.length - if (contentType.slice(0, formContentType.length) === formContentType) { - contentType = formContentType - form = body - } - if (uri.query) { - query = uri.query - } - if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) { - self.request.emit('error', new Error('oauth: transport_method of body requires POST ' + - 'and content-type ' + formContentType)) + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') } - if (!form && typeof _oauth.body_hash === 'boolean') { - _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString()) + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') } - var oa = self.buildParams(_oauth, uri, method, query, form, qsLib) - - switch (transport) { - case 'header': - self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"')) - break + this.maxMatches = Infinity + this.matches = 0 - case 'query': - var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&') - self.request.uri = url.parse(href) - self.request.path = self.request.uri.path - break + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 - case 'body': - self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&') - break + this._lookbehind = Buffer.alloc(needleLength) - default: - self.request.emit('error', new Error('oauth: transport_method invalid')) + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i } } +inherits(SBMH, EventEmitter) -exports.f = OAuth - - -/***/ }), - -/***/ 66476: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var qs = __nccwpck_require__(22760) -var querystring = __nccwpck_require__(63477) - -function Querystring (request) { - this.request = request - this.lib = null - this.useQuerystring = null - this.parseOptions = null - this.stringifyOptions = null -} - -Querystring.prototype.init = function (options) { - if (this.lib) { return } - - this.useQuerystring = options.useQuerystring - this.lib = (this.useQuerystring ? querystring : qs) - - this.parseOptions = options.qsParseOptions || {} - this.stringifyOptions = options.qsStringifyOptions || {} -} - -Querystring.prototype.stringify = function (obj) { - return (this.useQuerystring) - ? this.rfc3986(this.lib.stringify(obj, - this.stringifyOptions.sep || null, - this.stringifyOptions.eq || null, - this.stringifyOptions)) - : this.lib.stringify(obj, this.stringifyOptions) -} - -Querystring.prototype.parse = function (str) { - return (this.useQuerystring) - ? this.lib.parse(str, - this.parseOptions.sep || null, - this.parseOptions.eq || null, - this.parseOptions) - : this.lib.parse(str, this.parseOptions) +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 } -Querystring.prototype.rfc3986 = function (str) { - return str.replace(/[!'()*]/g, function (c) { - return '%' + c.charCodeAt(0).toString(16).toUpperCase() - }) +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r } -Querystring.prototype.unescape = querystring.unescape - -exports.h = Querystring - - -/***/ }), - -/***/ 3048: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var url = __nccwpck_require__(57310) -var isUrl = /^https?:/ +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] -function Redirect (request) { - this.request = request - this.followRedirect = true - this.followRedirects = true - this.followAllRedirects = false - this.followOriginalHttpMethod = false - this.allowRedirect = function () { return true } - this.maxRedirects = 10 - this.redirects = [] - this.redirectsFollowed = 0 - this.removeRefererHeader = false -} + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch -Redirect.prototype.onRequest = function (options) { - var self = this + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) - if (options.maxRedirects !== undefined) { - self.maxRedirects = options.maxRedirects - } - if (typeof options.followRedirect === 'function') { - self.allowRedirect = options.followRedirect - } - if (options.followRedirect !== undefined) { - self.followRedirects = !!options.followRedirect - } - if (options.followAllRedirects !== undefined) { - self.followAllRedirects = options.followAllRedirects - } - if (self.followRedirects || self.followAllRedirects) { - self.redirects = self.redirects || [] - } - if (options.removeRefererHeader !== undefined) { - self.removeRefererHeader = options.removeRefererHeader - } - if (options.followOriginalHttpMethod !== undefined) { - self.followOriginalHttpMethod = options.followOriginalHttpMethod - } -} + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) -Redirect.prototype.redirectTo = function (response) { - var self = this - var request = self.request - - var redirectTo = null - if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) { - var location = response.caseless.get('location') - request.debug('redirect', location) - - if (self.followAllRedirects) { - redirectTo = location - } else if (self.followRedirects) { - switch (request.method) { - case 'PATCH': - case 'PUT': - case 'POST': - case 'DELETE': - // Do not follow redirects - break - default: - redirectTo = location - break + return (this._bufpos = pos + needleLength) } + pos += this._occ[ch] } - } else if (response.statusCode === 401) { - var authHeader = request._auth.onResponse(response) - if (authHeader) { - request.setHeader('authorization', authHeader) - redirectTo = request.uri - } - } - return redirectTo -} - -Redirect.prototype.onResponse = function (response) { - var self = this - var request = self.request - - var redirectTo = self.redirectTo(response) - if (!redirectTo || !self.allowRedirect.call(request, response)) { - return false - } - - request.debug('redirect to', redirectTo) - - // ignore any potential response body. it cannot possibly be useful - // to us at this point. - // response.resume should be defined, but check anyway before calling. Workaround for browserify. - if (response.resume) { - response.resume() - } - if (self.redirectsFollowed >= self.maxRedirects) { - request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href)) - return false - } - self.redirectsFollowed += 1 + // No match. - if (!isUrl.test(redirectTo)) { - redirectTo = url.resolve(request.uri.href, redirectTo) - } + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + } - var uriPrev = request.uri - request.uri = url.parse(redirectTo) + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } - // handle the case where we change protocol from https to http or vice versa - if (request.uri.protocol !== uriPrev.protocol) { - delete request.agent - } + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff - self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo }) + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len - if (self.followAllRedirects && request.method !== 'HEAD' && - response.statusCode !== 401 && response.statusCode !== 307) { - request.method = self.followOriginalHttpMethod ? request.method : 'GET' - } - // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215 - delete request.src - delete request.req - delete request._started - if (response.statusCode !== 401 && response.statusCode !== 307) { - // Remove parameters from the previous response, unless this is the second request - // for a server that requires digest authentication. - delete request.body - delete request._form - if (request.headers) { - request.removeHeader('host') - request.removeHeader('content-type') - request.removeHeader('content-length') - if (request.uri.hostname !== request.originalHost.split(':')[0]) { - // Remove authorization if changing hostnames (but not if just - // changing ports or protocols). This matches the behavior of curl: - // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710 - request.removeHeader('authorization') - } + this._bufpos = len + return len } } - if (!self.removeRefererHeader) { - request.setHeader('referer', uriPrev.href) - } - - request.emit('redirect') - - request.init() - - return true -} - -exports.l = Redirect - - -/***/ }), - -/***/ 17619: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var url = __nccwpck_require__(57310) -var tunnel = __nccwpck_require__(11137) - -var defaultProxyHeaderWhiteList = [ - 'accept', - 'accept-charset', - 'accept-encoding', - 'accept-language', - 'accept-ranges', - 'cache-control', - 'content-encoding', - 'content-language', - 'content-location', - 'content-md5', - 'content-range', - 'content-type', - 'connection', - 'date', - 'expect', - 'max-forwards', - 'pragma', - 'referer', - 'te', - 'user-agent', - 'via' -] - -var defaultProxyHeaderExclusiveList = [ - 'proxy-authorization' -] + pos += (pos >= 0) * this._bufpos -function constructProxyHost (uriObject) { - var port = uriObject.port - var protocol = uriObject.protocol - var proxyHost = uriObject.hostname + ':' + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - if (port) { - proxyHost += port - } else if (protocol === 'https:') { - proxyHost += '443' + return (this._bufpos = pos + needleLength) } else { - proxyHost += '80' - } - - return proxyHost -} - -function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) { - var whiteList = proxyHeaderWhiteList - .reduce(function (set, header) { - set[header.toLowerCase()] = true - return set - }, {}) - - return Object.keys(headers) - .filter(function (header) { - return whiteList[header.toLowerCase()] - }) - .reduce(function (set, header) { - set[header] = headers[header] - return set - }, {}) -} - -function constructTunnelOptions (request, proxyHeaders) { - var proxy = request.proxy - - var tunnelOptions = { - proxy: { - host: proxy.hostname, - port: +proxy.port, - proxyAuth: proxy.auth, - headers: proxyHeaders - }, - headers: request.headers, - ca: request.ca, - cert: request.cert, - key: request.key, - passphrase: request.passphrase, - pfx: request.pfx, - ciphers: request.ciphers, - rejectUnauthorized: request.rejectUnauthorized, - secureOptions: request.secureOptions, - secureProtocol: request.secureProtocol + pos = len - needleLength } - return tunnelOptions -} - -function constructTunnelFnName (uri, proxy) { - var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http') - var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http') - return [uriProtocol, proxyProtocol].join('Over') -} - -function getTunnelFn (request) { - var uri = request.uri - var proxy = request.proxy - var tunnelFnName = constructTunnelFnName(uri, proxy) - return tunnel[tunnelFnName] -} - -function Tunnel (request) { - this.request = request - this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList - this.proxyHeaderExclusiveList = [] - if (typeof request.tunnel !== 'undefined') { - this.tunnelOverride = request.tunnel + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos } -} - -Tunnel.prototype.isEnabled = function () { - var self = this - var request = self.request - // Tunnel HTTPS by default. Allow the user to override this setting. - - // If self.tunnelOverride is set (the user specified a value), use it. - if (typeof self.tunnelOverride !== 'undefined') { - return self.tunnelOverride + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos } - // If the destination is HTTPS, tunnel. - if (request.uri.protocol === 'https:') { - return true - } + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } - // Otherwise, do not use tunnel. - return false + this._bufpos = len + return len } -Tunnel.prototype.setup = function (options) { - var self = this - var request = self.request - - options = options || {} - - if (typeof request.proxy === 'string') { - request.proxy = url.parse(request.proxy) - } - - if (!request.proxy || !request.tunnel) { - return false - } +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} - // Setup Proxy Header Exclusive List and White List - if (options.proxyHeaderWhiteList) { - self.proxyHeaderWhiteList = options.proxyHeaderWhiteList - } - if (options.proxyHeaderExclusiveList) { - self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } } - - var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList) - var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList) - - // Setup Proxy Headers and Proxy Headers Host - // Only send the Proxy White Listed Header names - var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList) - proxyHeaders.host = constructProxyHost(request.uri) - - proxyHeaderExclusiveList.forEach(request.removeHeader, request) - - // Set Agent from Tunnel Data - var tunnelFn = getTunnelFn(request) - var tunnelOptions = constructTunnelOptions(request, proxyHeaders) - request.agent = tunnelFn(tunnelOptions) - return true } -Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList -Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList -exports.n = Tunnel +module.exports = SBMH /***/ }), -/***/ 11377: +/***/ 33438: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var CombinedStream = __nccwpck_require__(85443); -var util = __nccwpck_require__(73837); -var path = __nccwpck_require__(71017); -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var parseUrl = (__nccwpck_require__(57310).parse); -var fs = __nccwpck_require__(57147); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var populate = __nccwpck_require__(94932); - -// Public API -module.exports = FormData; - -// make it a Stream -util.inherits(FormData, CombinedStream); - -/** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream - */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - - CombinedStream.call(this); - - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } -} - -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - -FormData.prototype.append = function(field, value, options) { - - options = options || {}; - - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } - - var append = CombinedStream.prototype.append.bind(this); - - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } - - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; - } - - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - - append(header); - append(value); - append(footer); - - // pass along options.knownLength - this._trackLength(header, value, options); -}; - -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; +"use strict"; - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } - this._valueLength += valueLength; +const WritableStream = (__nccwpck_require__(84492).Writable) +const { inherits } = __nccwpck_require__(47261) +const Dicer = __nccwpck_require__(2856) - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; +const MultipartParser = __nccwpck_require__(90415) +const UrlencodedParser = __nccwpck_require__(16780) +const parseParams = __nccwpck_require__(34426) - // empty or either doesn't have path or not an http response - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { - return; - } +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') } -}; - -FormData.prototype._lengthRetriever = function(value, callback) { - - if (value.hasOwnProperty('fd')) { - - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { - - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); - - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { - - var fileSize; - - if (err) { - callback(err); - return; - } - - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); - - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); - - // something else - } else { - callback('Unknown stream'); + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') } -}; - -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') } - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; + const { + headers, + ...streamOptions + } = opts - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); + this.opts = { + autoDestroy: false, + ...streamOptions } + WritableStream.call(this, this.opts) - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; - - // skip nullish headers. - if (header == null) { - continue; - } - - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return } + this._finished = true } + WritableStream.prototype.emit.apply(this, arguments) +} - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; - -FormData.prototype._getContentDisposition = function(value, options) { - - var filename - , contentDisposition - ; - - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path); - } - - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } - - return contentDisposition; -}; - -FormData.prototype._getContentType = function(value, options) { - - // use custom content-type above all - var contentType = options.contentType; - - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } - - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } - - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath } - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) } - - return contentType; -}; - -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; - - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } - - next(footer); - }.bind(this); -}; - -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; - -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; - - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) } + throw new Error('Unsupported Content-Type.') +} - return formHeaders; -}; +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); - } +module.exports = Busboy +module.exports["default"] = Busboy +module.exports.Busboy = Busboy - return this._boundary; -}; +module.exports.Dicer = Dicer -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } - this._boundary = boundary; -}; +/***/ }), -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; +/***/ 90415: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +"use strict"; - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } - return knownLength; -}; +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; +const { Readable } = __nccwpck_require__(84492) +const { inherits } = __nccwpck_require__(47261) - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } +const Dicer = __nccwpck_require__(2856) - return hasKnownLength; -}; +const parseParams = __nccwpck_require__(34426) +const decodeText = __nccwpck_require__(99136) +const basename = __nccwpck_require__(60496) +const getLimit = __nccwpck_require__(49692) -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } } - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() } + } - values.forEach(function(length) { - knownLength += length; - }); + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } - cb(null, knownLength); - }); -}; + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } - // use custom params - } else { + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') } - } - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } + } - // get content length and fire away - this.getLength(function(err, length) { - if (err) { - this._error(err); - return; - } + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } - // add content length - request.setHeader('Content-Length', length); + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } - this.pipe(request); - if (cb) { - request.on('error', cb); - request.on('response', cb.bind(this, null)); - } - }.bind(this)); + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - return request; -}; + let onData, + onEnd -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } -}; + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } -FormData.prototype.toString = function () { - return '[object FormData]'; -}; + ++nfiles + if (!boy._events.file) { + self.parser._ignore() + return + } -/***/ }), + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) -/***/ 94932: -/***/ ((module) => { + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } -// populates missing values -module.exports = function(dst, src) { + file.bytesRead = nsize + } - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } - return dst; -}; + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } -/***/ }), + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } -/***/ 67087: -/***/ ((module) => { + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} + +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } } -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - return ([ - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]] - ]).join(''); +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } } -module.exports = bytesToUuid; +function skipPart (part) { + part.resume() +} +function FileStream (opts) { + Readable.call(this, opts) -/***/ }), + this.bytesRead = 0 -/***/ 9117: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.truncated = false +} -// Unique ID creation requires a high quality random # generator. In node.js -// this is pretty straight-forward - we use the crypto API. +inherits(FileStream, Readable) -var crypto = __nccwpck_require__(6113); +FileStream.prototype._read = function (n) {} -module.exports = function nodeRNG() { - return crypto.randomBytes(16); -}; +module.exports = Multipart /***/ }), -/***/ 71435: +/***/ 16780: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var rng = __nccwpck_require__(9117); -var bytesToUuid = __nccwpck_require__(67087); +"use strict"; -function v4(options, buf, offset) { - var i = buf && offset || 0; - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; +const Decoder = __nccwpck_require__(89730) +const decodeText = __nccwpck_require__(99136) +const getLimit = __nccwpck_require__(49692) - var rnds = options.random || (options.rng || rng)(); +const RE_CHARSET = /^charset$/i - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) + + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break } } - return buf || bytesToUuid(rnds); + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } + + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false } -module.exports = v4; +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() + } + let idxeq; let idxamp; let i; let p = 0; const len = data.length -/***/ }), + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } -/***/ 70304: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' -"use strict"; + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } -var http = __nccwpck_require__(13685) -var https = __nccwpck_require__(95687) -var url = __nccwpck_require__(57310) -var util = __nccwpck_require__(73837) -var stream = __nccwpck_require__(12781) -var zlib = __nccwpck_require__(59796) -var aws2 = __nccwpck_require__(96342) -var aws4 = __nccwpck_require__(16071) -var httpSignature = __nccwpck_require__(42479) -var mime = __nccwpck_require__(43583) -var caseless = __nccwpck_require__(35684) -var ForeverAgent = __nccwpck_require__(47568) -var FormData = __nccwpck_require__(11377) -var extend = __nccwpck_require__(38171) -var isstream = __nccwpck_require__(83362) -var isTypedArray = (__nccwpck_require__(10657).strict) -var helpers = __nccwpck_require__(74845) -var cookies = __nccwpck_require__(50976) -var getProxyFromURI = __nccwpck_require__(75654) -var Querystring = (__nccwpck_require__(66476)/* .Querystring */ .h) -var Har = (__nccwpck_require__(3248)/* .Har */ .t) -var Auth = (__nccwpck_require__(76996)/* .Auth */ .g) -var OAuth = (__nccwpck_require__(41174)/* .OAuth */ .f) -var hawk = __nccwpck_require__(34473) -var Multipart = (__nccwpck_require__(87810)/* .Multipart */ .$) -var Redirect = (__nccwpck_require__(3048)/* .Redirect */ .l) -var Tunnel = (__nccwpck_require__(17619)/* .Tunnel */ .n) -var now = __nccwpck_require__(85644) -var Buffer = (__nccwpck_require__(21867).Buffer) - -var safeStringify = helpers.safeStringify -var isReadStream = helpers.isReadStream -var toBase64 = helpers.toBase64 -var defer = helpers.defer -var copy = helpers.copy -var version = helpers.version -var globalCookieJar = cookies.jar() - -var globalPool = {} - -function filterForNonReserved (reserved, options) { - // Filter out properties that are not reserved. - // Reserved values are passed in at call site. - - var object = {} - for (var i in options) { - var notReserved = (reserved.indexOf(i) === -1) - if (notReserved) { - object[i] = options[i] - } - } - return object -} - -function filterOutReservedFunctions (reserved, options) { - // Filter out properties that are functions and are reserved. - // Reserved values are passed in at call site. - - var object = {} - for (var i in options) { - var isReserved = !(reserved.indexOf(i) === -1) - var isFunction = (typeof options[i] === 'function') - if (!(isReserved && isFunction)) { - object[i] = options[i] - } - } - return object -} - -// Return a simpler request object to allow serialization -function requestToJSON () { - var self = this - return { - uri: self.uri, - method: self.method, - headers: self.headers + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } + + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len + } + } } + cb() } -// Return a simpler response object to allow serialization -function responseToJSON () { - var self = this - return { - statusCode: self.statusCode, - body: self.body, - headers: self.headers, - request: requestToJSON.call(self.request) +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) } + this.boy._done = true + this.boy.emit('finish') } -function Request (options) { - // if given the method property in options, set property explicitMethod to true +module.exports = UrlEncoded - // extend the Request instance with any non-reserved properties - // remove any reserved functions from the options object - // set Request instance to be readable and writable - // call init - var self = this +/***/ }), - // start with HAR, then override with additional options - if (options.har) { - self._har = new Har(self) - options = self._har.options(options) - } +/***/ 89730: +/***/ ((module) => { - stream.Stream.call(self) - var reserved = Object.keys(Request.prototype) - var nonReserved = filterForNonReserved(reserved, options) +"use strict"; - extend(self, nonReserved) - options = filterOutReservedFunctions(reserved, options) - self.readable = true - self.writable = true - if (options.method) { - self.explicitMethod = true - } - self._qs = new Querystring(self) - self._auth = new Auth(self) - self._oauth = new OAuth(self) - self._multipart = new Multipart(self) - self._redirect = new Redirect(self) - self._tunnel = new Tunnel(self) - self.init(options) -} +const RE_PLUS = /\+/g -util.inherits(Request, stream.Stream) +const HEX = [ + 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, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 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, 1, 1, 1, 1, 1, 1, 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 +] -// Debugging -Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG) -function debug () { - if (Request.debug) { - console.error('REQUEST %s', util.format.apply(util, arguments)) +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p + } } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined } -Request.prototype.debug = debug -Request.prototype.init = function (options) { - // init() contains all the code to setup the request object. - // the actual outgoing request is not started until start() is called - // this function is called from both the constructor and on redirect. - var self = this - if (!options) { - options = {} - } - self.headers = self.headers ? copy(self.headers) : {} +module.exports = Decoder - // Delete headers with value undefined since they break - // ClientRequest.OutgoingMessage.setHeader in node 0.12 - for (var headerName in self.headers) { - if (typeof self.headers[headerName] === 'undefined') { - delete self.headers[headerName] - } - } - caseless.httpify(self, self.headers) +/***/ }), - if (!self.method) { - self.method = options.method || 'GET' - } - if (!self.localAddress) { - self.localAddress = options.localAddress - } +/***/ 60496: +/***/ ((module) => { - self._qs.init(options) +"use strict"; - debug(options) - if (!self.pool && self.pool !== false) { - self.pool = globalPool - } - self.dests = self.dests || [] - self.__isRequestRequest = true - // Protect against double callback - if (!self._callback && self.callback) { - self._callback = self.callback - self.callback = function () { - if (self._callbackCalled) { - return // Print a warning maybe? - } - self._callbackCalled = true - self._callback.apply(self, arguments) +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) } - self.on('error', self.callback.bind()) - self.on('complete', self.callback.bind(self, null)) } + return (path === '..' || path === '.' ? '' : path) +} - // People use this property instead all the time, so support it - if (!self.uri && self.url) { - self.uri = self.url - delete self.url - } - // If there's a baseUrl, then use it as the base URL (i.e. uri must be - // specified as a relative path and is appended to baseUrl). - if (self.baseUrl) { - if (typeof self.baseUrl !== 'string') { - return self.emit('error', new Error('options.baseUrl must be a string')) - } +/***/ }), - if (typeof self.uri !== 'string') { - return self.emit('error', new Error('options.uri must be a string when using options.baseUrl')) - } +/***/ 99136: +/***/ ((module) => { + +"use strict"; - if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) { - return self.emit('error', new Error('options.uri must be a path when using options.baseUrl')) - } - // Handle all cases to make sure that there's only one slash between - // baseUrl and uri. - var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1 - var uriStartsWithSlash = self.uri.indexOf('/') === 0 +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) - if (baseUrlEndsWithSlash && uriStartsWithSlash) { - self.uri = self.baseUrl + self.uri.slice(1) - } else if (baseUrlEndsWithSlash || uriStartsWithSlash) { - self.uri = self.baseUrl + self.uri - } else if (self.uri === '') { - self.uri = self.baseUrl +function decodeText (text, textEncoding, destEncoding) { + if (text) { + if (textDecoders.has(destEncoding)) { + try { + return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding)) + } catch (e) { } } else { - self.uri = self.baseUrl + '/' + self.uri + try { + textDecoders.set(destEncoding, new TextDecoder(destEncoding)) + return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding)) + } catch (e) { } } - delete self.baseUrl } + return text +} - // A URI is needed by this point, emit error if we haven't been able to get one - if (!self.uri) { - return self.emit('error', new Error('options.uri is a required argument')) - } +module.exports = decodeText - // If a string URI/URL was given, parse it into a URL object - if (typeof self.uri === 'string') { - self.uri = url.parse(self.uri) - } - // Some URL objects are not from a URL parsed string and need href added - if (!self.uri.href) { - self.uri.href = url.format(self.uri) - } +/***/ }), - // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme - if (self.uri.protocol === 'unix:') { - return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`')) - } +/***/ 49692: +/***/ ((module) => { - // Support Unix Sockets - if (self.uri.host === 'unix') { - self.enableUnixSocket() - } +"use strict"; - if (self.strictSSL === false) { - self.rejectUnauthorized = false - } - if (!self.uri.pathname) { self.uri.pathname = '/' } +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } - if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) { - // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar - // Detect and reject it as soon as possible - var faultyUri = url.format(self.uri) - var message = 'Invalid URI "' + faultyUri + '"' - if (Object.keys(options).length === 0) { - // No option ? This can be the sign of a redirect - // As this is a case where the user cannot do anything (they didn't call request directly with this URL) - // they should be warned that it can be caused by a redirection (can save some hair) - message += '. This can be caused by a crappy redirection.' - } - // This error was fatal - self.abort() - return self.emit('error', new Error(message)) - } + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - if (!self.hasOwnProperty('proxy')) { - self.proxy = getProxyFromURI(self.uri) - } + return limits[name] +} - self.tunnel = self._tunnel.isEnabled() - if (self.proxy) { - self._tunnel.setup(options) - } - self._redirect.onRequest(options) +/***/ }), - self.setHost = false - if (!self.hasHeader('host')) { - var hostHeaderName = self.originalHostHeaderName || 'host' - self.setHeader(hostHeaderName, self.uri.host) - // Drop :port suffix from Host header if known protocol. - if (self.uri.port) { - if ((self.uri.port === '80' && self.uri.protocol === 'http:') || - (self.uri.port === '443' && self.uri.protocol === 'https:')) { - self.setHeader(hostHeaderName, self.uri.hostname) - } - } - self.setHost = true - } +/***/ 34426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - self.jar(self._jar || options.jar) +"use strict"; - if (!self.uri.port) { - if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 } - } - if (self.proxy && !self.tunnel) { - self.port = self.proxy.port - self.host = self.proxy.hostname - } else { - self.port = self.uri.port - self.host = self.uri.hostname - } +const decodeText = __nccwpck_require__(99136) - if (options.form) { - self.form(options.form) - } +const RE_ENCODED = /%([a-fA-F0-9]{2})/g - if (options.formData) { - var formData = options.formData - var requestForm = self.form() - var appendFormValue = function (key, value) { - if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) { - requestForm.append(key, value.value, value.options) - } else { - requestForm.append(key, value) +function encodedReplacer (match, byte) { + return String.fromCharCode(parseInt(byte, 16)) +} + +function parseParams (str) { + const res = [] + let state = 'key' + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + + for (var i = 0, len = str.length; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue } - } - for (var formKey in formData) { - if (formData.hasOwnProperty(formKey)) { - var formValue = formData[formKey] - if (formValue instanceof Array) { - for (var j = 0; j < formValue.length; j++) { - appendFormValue(formKey, formValue[j]) + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = 'key' + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === 'charset' || state === 'lang') && char === "'") { + if (state === 'charset') { + state = 'lang' + charset = tmp.substring(1) + } else { state = 'value' } + tmp = '' + continue + } else if (state === 'key' && + (char === '*' || char === '=') && + res.length) { + if (char === '*') { state = 'charset' } else { state = 'value' } + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = 'key' + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) } - } else { - appendFormValue(formKey, formValue) + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') } - } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } } + tmp += char } - - if (options.qs) { - self.qs(options.qs) - } - - if (self.uri.path) { - self.path = self.uri.path - } else { - self.path = self.uri.pathname + (self.uri.search || '') - } - - if (self.path.length === 0) { - self.path = '/' - } - - // Auth must happen last in case signing is dependent on other headers - if (options.aws) { - self.aws(options.aws) + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') } - if (options.hawk) { - self.hawk(options.hawk) - } + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } - if (options.httpSignature) { - self.httpSignature(options.httpSignature) - } + return res +} - if (options.auth) { - if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) { - options.auth.user = options.auth.username - } - if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) { - options.auth.pass = options.auth.password - } +module.exports = parseParams - self.auth( - options.auth.user, - options.auth.pass, - options.auth.sendImmediately, - options.auth.bearer - ) - } - if (self.gzip && !self.hasHeader('accept-encoding')) { - self.setHeader('accept-encoding', 'gzip, deflate') - } +/***/ }), - if (self.uri.auth && !self.hasHeader('authorization')) { - var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) }) - self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true) - } +/***/ 40334: +/***/ ((module) => { - if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) { - var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) }) - var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':')) - self.setHeader('proxy-authorization', authHeader) - } +"use strict"; - if (self.proxy && !self.tunnel) { - self.path = (self.uri.protocol + '//' + self.uri.host + self.path) +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - if (options.json) { - self.json(options.json) - } - if (options.multipart) { - self.multipart(options.multipart) - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createTokenAuth: () => createTokenAuth +}); +module.exports = __toCommonJS(dist_src_exports); - if (options.time) { - self.timing = true +// pkg/dist-src/auth.js +var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; +var REGEX_IS_INSTALLATION = /^ghs_/; +var REGEX_IS_USER_TO_SERVER = /^ghu_/; +async function auth(token) { + const isApp = token.split(/\./).length === 3; + const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); + const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} - // NOTE: elapsedTime is deprecated in favor of .timings - self.elapsedTime = self.elapsedTime || 0 +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; } + return `token ${token}`; +} - function setContentLength () { - if (isTypedArray(self.body)) { - self.body = Buffer.from(self.body) - } - - if (!self.hasHeader('content-length')) { - var length - if (typeof self.body === 'string') { - length = Buffer.byteLength(self.body) - } else if (Array.isArray(self.body)) { - length = self.body.reduce(function (a, b) { return a + b.length }, 0) - } else { - length = self.body.length - } +// pkg/dist-src/hook.js +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} - if (length) { - self.setHeader('content-length', length) - } else { - self.emit('error', new Error('Argument error, options.body.')) - } - } +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); } - if (self.body && !isstream(self.body)) { - setContentLength() + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - if (options.oauth) { - self.oauth(options.oauth) - } else if (self._oauth.params && self.hasHeader('authorization')) { - self.oauth(self._oauth.params) - } - var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol - var defaultModules = {'http:': http, 'https:': https} - var httpModules = self.httpModules || {} +/***/ }), - self.httpModule = httpModules[protocol] || defaultModules[protocol] +/***/ 76762: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!self.httpModule) { - return self.emit('error', new Error('Invalid protocol: ' + protocol)) - } +"use strict"; - if (options.ca) { - self.ca = options.ca +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - if (!self.agent) { - if (options.agentOptions) { - self.agentOptions = options.agentOptions - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + Octokit: () => Octokit +}); +module.exports = __toCommonJS(dist_src_exports); +var import_universal_user_agent = __nccwpck_require__(45030); +var import_before_after_hook = __nccwpck_require__(83682); +var import_request = __nccwpck_require__(36234); +var import_graphql = __nccwpck_require__(88467); +var import_auth_token = __nccwpck_require__(40334); - if (options.agentClass) { - self.agentClass = options.agentClass - } else if (options.forever) { - var v = version() - // use ForeverAgent in node 0.10- only - if (v.major === 0 && v.minor <= 10) { - self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL - } else { - self.agentClass = self.httpModule.Agent - self.agentOptions = self.agentOptions || {} - self.agentOptions.keepAlive = true - } - } else { - self.agentClass = self.httpModule.Agent - } - } +// pkg/dist-src/version.js +var VERSION = "5.1.0"; - if (self.pool === false) { - self.agent = false - } else { - self.agent = self.agent || self.getNewAgent() +// pkg/dist-src/index.js +var noop = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var Octokit = class { + static { + this.VERSION = VERSION; } - - self.on('pipe', function (src) { - if (self.ntick && self._started) { - self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.')) - } - self.src = src - if (isReadStream(src)) { - if (!self.hasHeader('content-type')) { - self.setHeader('content-type', mime.lookup(src.path)) - } - } else { - if (src.headers) { - for (var i in src.headers) { - if (!self.hasHeader(i)) { - self.setHeader(i, src.headers[i]) - } + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); } - if (self._json && !self.hasHeader('content-type')) { - self.setHeader('content-type', 'application/json') + }; + return OctokitWithDefaults; + } + static { + this.plugins = []; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static { + this.plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); } - if (src.method && !self.explicitMethod) { - self.method = src.method + }; + return NewOctokit; + } + constructor(options = {}) { + const hook = new import_before_after_hook.Collection(); + const requestDefaults = { + baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" } + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; } - - // self.on('pipe', function () { - // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.') - // }) - }) - - defer(function () { - if (self._aborted) { - return + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; } - - var end = function () { - if (self._form) { - if (!self._auth.hasAuth) { - self._form.pipe(self) - } else if (self._auth.hasAuth && self._auth.sentAuth) { - self._form.pipe(self) - } - } - if (self._multipart && self._multipart.chunked) { - self._multipart.body.pipe(self) - } - if (self.body) { - if (isstream(self.body)) { - self.body.pipe(self) - } else { - setContentLength() - if (Array.isArray(self.body)) { - self.body.forEach(function (part) { - self.write(part) - }) - } else { - self.write(self.body) - } - self.end() - } - } else if (self.requestBodyStream) { - console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.') - self.requestBodyStream.pipe(self) - } else if (!self.src) { - if (self._auth.hasAuth && !self._auth.sentAuth) { - self.end() - return - } - if (self.method !== 'GET' && typeof self.method !== 'undefined') { - self.setHeader('content-length', 0) - } - self.end() + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = import_request.request.defaults(requestDefaults); + this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); + this.log = Object.assign( + { + debug: noop, + info: noop, + warn: consoleWarn, + error: consoleError + }, + options.log + ); + this.hook = hook; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth = (0, import_auth_token.createTokenAuth)(options.auth); + hook.wrap("request", auth.hook); + this.auth = auth; } - } - - if (self._form && !self.hasHeader('content-length')) { - // Before ending the request, we had to compute the length of the whole form, asyncly - self.setHeader(self._form.getHeaders(), true) - self._form.getLength(function (err, length) { - if (!err && !isNaN(length)) { - self.setHeader('content-length', length) - } - end() - }) } else { - end() + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook.wrap("request", auth.hook); + this.auth = auth; } - - self.ntick = true - }) -} - -Request.prototype.getNewAgent = function () { - var self = this - var Agent = self.agentClass - var options = {} - if (self.agentOptions) { - for (var i in self.agentOptions) { - options[i] = self.agentOptions[i] + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); } } - if (self.ca) { - options.ca = self.ca - } - if (self.ciphers) { - options.ciphers = self.ciphers - } - if (self.secureProtocol) { - options.secureProtocol = self.secureProtocol - } - if (self.secureOptions) { - options.secureOptions = self.secureOptions - } - if (typeof self.rejectUnauthorized !== 'undefined') { - options.rejectUnauthorized = self.rejectUnauthorized - } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - if (self.cert && self.key) { - options.key = self.key - options.cert = self.cert - } - if (self.pfx) { - options.pfx = self.pfx - } +/***/ }), - if (self.passphrase) { - options.passphrase = self.passphrase - } +/***/ 59440: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var poolKey = '' +"use strict"; - // different types of agents are in different pools - if (Agent !== self.httpModule.Agent) { - poolKey += Agent.name +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - // ca option is only relevant if proxy or destination are https - var proxy = self.proxy - if (typeof proxy === 'string') { - proxy = url.parse(proxy) - } - var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:' +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); - if (isHttps) { - if (options.ca) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.ca - } +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(45030); - if (typeof options.rejectUnauthorized !== 'undefined') { - if (poolKey) { - poolKey += ':' - } - poolKey += options.rejectUnauthorized - } +// pkg/dist-src/version.js +var VERSION = "9.0.6"; - if (options.cert) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.cert.toString('ascii') + options.key.toString('ascii') - } +// pkg/dist-src/defaults.js +var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } +}; - if (options.pfx) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.pfx.toString('ascii') - } +// pkg/dist-src/util/lowercase-keys.js +function lowercaseKeys(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} - if (options.ciphers) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.ciphers - } +// pkg/dist-src/util/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} - if (options.secureProtocol) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.secureProtocol +// pkg/dist-src/util/merge-deep.js +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject(options[key])) { + if (!(key in defaults)) + Object.assign(result, { [key]: options[key] }); + else + result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); } + }); + return result; +} - if (options.secureOptions) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.secureOptions +// pkg/dist-src/util/remove-undefined-properties.js +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; } } + return obj; +} - if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) { - // not doing anything special. Use the globalAgent - return self.httpModule.globalAgent +// pkg/dist-src/merge.js +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); } - - // we're using a stored agent. Make sure it's protocol-specific - poolKey = self.uri.protocol + poolKey - - // generate a new agent for this setting if none yet exists - if (!self.pool[poolKey]) { - self.pool[poolKey] = new Agent(options) - // properly set maxSockets on new agents - if (self.pool.maxSockets) { - self.pool[poolKey].maxSockets = self.pool.maxSockets + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); } - - return self.pool[poolKey] + return mergedOptions; } -Request.prototype.start = function () { - // start() is called once we are ready to send the outgoing HTTP request. - // this is usually called on the first write(), end() or on nextTick() - var self = this - - if (self.timing) { - // All timings will be relative to this request's startTime. In order to do this, - // we need to capture the wall-clock start time (via Date), immediately followed - // by the high-resolution timer (via now()). While these two won't be set - // at the _exact_ same time, they should be close enough to be able to calculate - // high-resolution, monotonically non-decreasing timestamps relative to startTime. - var startTime = new Date().getTime() - var startTimeNow = now() - } - - if (self._aborted) { - return - } - - self._started = true - self.method = self.method || 'GET' - self.href = self.uri.href - - if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) { - self.setHeader('content-length', self.src.stat.size) - } - if (self._aws) { - self.aws(self._aws, true) +// pkg/dist-src/util/add-query-parameters.js +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; } + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} - // We have a method named auth, which is completely different from the http.request - // auth option. If we don't remove it, we're gonna have a bad time. - var reqOptions = copy(self) - delete reqOptions.auth - - debug('make request', self.uri.href) - - // node v6.8.0 now supports a `timeout` value in `http.request()`, but we - // should delete it for now since we handle timeouts manually for better - // consistency with node versions before v6.8.0 - delete reqOptions.timeout - - try { - self.req = self.httpModule.request(reqOptions) - } catch (err) { - self.emit('error', err) - return +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +} - if (self.timing) { - self.startTime = startTime - self.startTimeNow = startTimeNow - - // Timing values will all be relative to startTime (by comparing to startTimeNow - // so we have an accurate clock) - self.timings = {} +// pkg/dist-src/util/omit.js +function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } } + return result; +} - var timeout - if (self.timeout && !self.timeoutTimer) { - if (self.timeout < 0) { - timeout = 0 - } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) { - timeout = self.timeout +// pkg/dist-src/util/url-template.js +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); } + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; } - - self.req.on('response', self.onRequestResponse.bind(self)) - self.req.on('error', self.onRequestError.bind(self)) - self.req.on('drain', function () { - self.emit('drain') - }) - - self.req.on('socket', function (socket) { - // `._connecting` was the old property which was made public in node v6.1.0 - var isConnecting = socket._connecting || socket.connecting - if (self.timing) { - self.timings.socket = now() - self.startTimeNow - - if (isConnecting) { - var onLookupTiming = function () { - self.timings.lookup = now() - self.startTimeNow +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value = context[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); } - - var onConnectTiming = function () { - self.timings.connect = now() - self.startTimeNow + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); } - - socket.once('lookup', onLookupTiming) - socket.once('connect', onConnectTiming) - - // clean up timing event listeners if needed on error - self.req.once('error', function () { - socket.removeListener('lookup', onLookupTiming) - socket.removeListener('connect', onConnectTiming) - }) } } - - var setReqTimeout = function () { - // This timeout sets the amount of time to wait *between* bytes sent - // from the server once connected. - // - // In particular, it's useful for erroring if the server fails to send - // data halfway through streaming a response. - self.req.setTimeout(timeout, function () { - if (self.req) { - self.abort() - var e = new Error('ESOCKETTIMEDOUT') - e.code = 'ESOCKETTIMEDOUT' - e.connect = false - self.emit('error', e) - } - }) + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); } - if (timeout !== undefined) { - // Only start the connection timer if we're actually connecting a new - // socket, otherwise if we're already connected (because this is a - // keep-alive connection) do not bother. This is important since we won't - // get a 'connect' event for an already connected socket. - if (isConnecting) { - var onReqSockConnect = function () { - socket.removeListener('connect', onReqSockConnect) - self.clearTimeout() - setReqTimeout() + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); } - - socket.on('connect', onReqSockConnect) - - self.req.on('error', function (err) { // eslint-disable-line handle-callback-err - socket.removeListener('connect', onReqSockConnect) - }) - - // Set a timeout in memory - this block will throw if the server takes more - // than `timeout` to write the HTTP status and headers (corresponding to - // the on('response') event on the client). NB: this measures wall-clock - // time, not the time between bytes sent by the server. - self.timeoutTimer = setTimeout(function () { - socket.removeListener('connect', onReqSockConnect) - self.abort() - var e = new Error('ETIMEDOUT') - e.code = 'ETIMEDOUT' - e.connect = true - self.emit('error', e) - }, timeout) } else { - // We're already connected - setReqTimeout() + return encodeReserved(literal); } } - self.emit('socket', socket) - }) - - self.emit('request', self.req) -} - -Request.prototype.onRequestError = function (error) { - var self = this - if (self._aborted) { - return - } - if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' && - self.agent.addRequestNoreuse) { - self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } - self.start() - self.req.end() - return + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); } - self.clearTimeout() - self.emit('error', error) } -Request.prototype.onRequestResponse = function (response) { - var self = this - - if (self.timing) { - self.timings.response = now() - self.startTimeNow +// pkg/dist-src/parse.js +function parse(options) { + let method = options.method.toUpperCase(); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; } - - debug('onRequestResponse', self.uri.href, response.statusCode, response.headers) - response.on('end', function () { - if (self.timing) { - self.timings.end = now() - self.startTimeNow - response.timingStart = self.startTime - - // fill in the blanks for any periods that didn't trigger, such as - // no lookup or connect due to keep alive - if (!self.timings.socket) { - self.timings.socket = 0 - } - if (!self.timings.lookup) { - self.timings.lookup = self.timings.socket - } - if (!self.timings.connect) { - self.timings.connect = self.timings.lookup - } - if (!self.timings.response) { - self.timings.response = self.timings.connect - } - - debug('elapsed time', self.timings.end) - - // elapsedTime includes all redirects - self.elapsedTime += Math.round(self.timings.end) - - // NOTE: elapsedTime is deprecated in favor of .timings - response.elapsedTime = self.elapsedTime - - // timings is just for the final fetch - response.timings = self.timings - - // pre-calculate phase timings as well - response.timingPhases = { - wait: self.timings.socket, - dns: self.timings.lookup - self.timings.socket, - tcp: self.timings.connect - self.timings.lookup, - firstByte: self.timings.response - self.timings.connect, - download: self.timings.end - self.timings.response, - total: self.timings.end - } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); } - debug('response end', self.uri.href, response.statusCode, response.headers) - }) - - if (self._aborted) { - debug('aborted', self.uri.href) - response.resume() - return - } - - self.response = response - response.request = self - response.toJSON = responseToJSON - - // XXX This is different on 0.10, because SSL is strict by default - if (self.httpModule === https && - self.strictSSL && (!response.hasOwnProperty('socket') || - !response.socket.authorized)) { - debug('strict ssl error', self.uri.href) - var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL' - self.emit('error', new Error('SSL Error: ' + sslErr)) - return - } - - // Save the original host before any redirect (if it changes, we need to - // remove any authorization headers). Also remember the case of the header - // name because lots of broken servers expect Host instead of host and we - // want the caller to be able to specify this. - self.originalHost = self.getHeader('host') - if (!self.originalHostHeaderName) { - self.originalHostHeaderName = self.hasHeader('host') - } - if (self.setHost) { - self.removeHeader('host') - } - self.clearTimeout() - - var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar - var addCookie = function (cookie) { - // set the cookie if it's domain in the href's domain. - try { - targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true}) - } catch (e) { - self.emit('error', e) + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } } } - - response.caseless = caseless(response.headers) - - if (response.caseless.has('set-cookie') && (!self._disableCookies)) { - var headerName = response.caseless.has('set-cookie') - if (Array.isArray(response.headers[headerName])) { - response.headers[headerName].forEach(addCookie) + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; } else { - addCookie(response.headers[headerName]) + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } } } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); +} - if (self._redirect.onResponse(response)) { - return // Ignore the rest of the response - } else { - // Be a good stream and emit end when the response is finished. - // Hack to emit end on close because of a core bug that never fires end - response.on('close', function () { - if (!self._ended) { - self.response.emit('end') - } - }) +// pkg/dist-src/endpoint-with-defaults.js +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} - response.once('end', function () { - self._ended = true - }) +// pkg/dist-src/with-defaults.js +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); +} - var noBody = function (code) { - return ( - self.method === 'HEAD' || - // Informational - (code >= 100 && code < 200) || - // No Content - code === 204 || - // Not Modified - code === 304 - ) - } +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - var responseContent - if (self.gzip && !noBody(response.statusCode)) { - var contentEncoding = response.headers['content-encoding'] || 'identity' - contentEncoding = contentEncoding.trim().toLowerCase() - // Be more lenient with decoding compressed responses, since (very rarely) - // servers send slightly invalid gzip responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - var zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - } +/***/ }), - if (contentEncoding === 'gzip') { - responseContent = zlib.createGunzip(zlibOptions) - response.pipe(responseContent) - } else if (contentEncoding === 'deflate') { - responseContent = zlib.createInflate(zlibOptions) - response.pipe(responseContent) - } else { - // Since previous versions didn't check for Content-Encoding header, - // ignore any invalid values to preserve backwards-compatibility - if (contentEncoding !== 'identity') { - debug('ignoring unrecognized Content-Encoding ' + contentEncoding) - } - responseContent = response - } - } else { - responseContent = response - } +/***/ 88467: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (self.encoding) { - if (self.dests.length !== 0) { - console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.') - } else { - responseContent.setEncoding(self.encoding) - } - } +"use strict"; - if (self._paused) { - responseContent.pause() - } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - self.responseContent = responseContent +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest +}); +module.exports = __toCommonJS(dist_src_exports); +var import_request3 = __nccwpck_require__(36234); +var import_universal_user_agent = __nccwpck_require__(45030); - self.emit('response', response) +// pkg/dist-src/version.js +var VERSION = "7.0.2"; - self.dests.forEach(function (dest) { - self.pipeDest(dest) - }) +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(36234); - responseContent.on('data', function (chunk) { - if (self.timing && !self.responseStarted) { - self.responseStartTime = (new Date()).getTime() +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(36234); - // NOTE: responseStartTime is deprecated in favor of .timings - response.responseStartTime = self.responseStartTime - } - self._destdata = true - self.emit('data', chunk) - }) - responseContent.once('end', function (chunk) { - self.emit('end', chunk) - }) - responseContent.on('error', function (error) { - self.emit('error', error) - }) - responseContent.on('close', function () { self.emit('close') }) - - if (self.callback) { - self.readResponseBody(response) - } else { // if no callback - self.on('end', function () { - if (self._aborted) { - debug('aborted', self.uri.href) - return - } - self.emit('complete', response) - }) - } - } - debug('finish init function', self.uri.href) +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); } - -Request.prototype.readResponseBody = function (response) { - var self = this - debug("reading response's body") - var buffers = [] - var bufferLength = 0 - var strings = [] - - self.on('data', function (chunk) { - if (!Buffer.isBuffer(chunk)) { - strings.push(chunk) - } else if (chunk.length) { - bufferLength += chunk.length - buffers.push(chunk) - } - }) - self.on('end', function () { - debug('end event', self.uri.href) - if (self._aborted) { - debug('aborted', self.uri.href) - // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request. - // This can lead to leaky behavior if the user retains a reference to the request object. - buffers = [] - bufferLength = 0 - return - } - - if (bufferLength) { - debug('has body', self.uri.href, bufferLength) - response.body = Buffer.concat(buffers, bufferLength) - if (self.encoding !== null) { - response.body = response.body.toString(self.encoding) - } - // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request. - // This can lead to leaky behavior if the user retains a reference to the request object. - buffers = [] - bufferLength = 0 - } else if (strings.length) { - // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation. - // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse(). - if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') { - strings[0] = strings[0].substring(1) - } - response.body = strings.join('') +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } + } +}; - if (self._json) { - try { - response.body = JSON.parse(response.body, self._jsonReviver) - } catch (e) { - debug('invalid JSON received', self.uri.href) - } +// pkg/dist-src/graphql.js +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); } - debug('emitting complete', self.uri.href) - if (typeof response.body === 'undefined' && !self._json) { - response.body = self.encoding === null ? Buffer.alloc(0) : '' + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) + continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); } - self.emit('complete', response, response.body) - }) -} - -Request.prototype.abort = function () { - var self = this - self._aborted = true - - if (self.req) { - self.req.abort() - } else if (self.response) { - self.response.destroy() } - - self.clearTimeout() - self.emit('abort') -} - -Request.prototype.pipeDest = function (dest) { - var self = this - var response = self.response - // Called after the response is received - if (dest.headers && !dest.headersSent) { - if (response.caseless.has('content-type')) { - var ctname = response.caseless.has('content-type') - if (dest.setHeader) { - dest.setHeader(ctname, response.headers[ctname]) - } else { - dest.headers[ctname] = response.headers[ctname] - } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; } - - if (response.caseless.has('content-length')) { - var clname = response.caseless.has('content-length') - if (dest.setHeader) { - dest.setHeader(clname, response.headers[clname]) - } else { - dest.headers[clname] = response.headers[clname] - } + if (!result.variables) { + result.variables = {}; } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); } - if (dest.setHeader && !dest.headersSent) { - for (var i in response.headers) { - // If the response content is being decoded, the Content-Encoding header - // of the response doesn't represent the piped content, so don't pass it. - if (!self.gzip || i !== 'content-encoding') { - dest.setHeader(i, response.headers[i]) + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); } - dest.statusCode = response.statusCode - } - if (self.pipefilter) { - self.pipefilter(response, dest) - } + return response.data.data; + }); } -Request.prototype.qs = function (q, clobber) { - var self = this - var base - if (!clobber && self.uri.query) { - base = self._qs.parse(self.uri.query) - } else { - base = {} - } - - for (var i in q) { - base[i] = q[i] - } - - var qs = self._qs.stringify(base) +// pkg/dist-src/with-defaults.js +function withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} - if (qs === '') { - return self - } +// pkg/dist-src/index.js +var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs) - self.url = self.uri - self.path = self.uri.path - if (self.uri.host === 'unix') { - self.enableUnixSocket() - } +/***/ }), - return self -} -Request.prototype.form = function (form) { - var self = this - if (form) { - if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { - self.setHeader('content-type', 'application/x-www-form-urlencoded') - } - self.body = (typeof form === 'string') - ? self._qs.rfc3986(form.toString('utf8')) - : self._qs.stringify(form).toString('utf8') - return self - } - // create form-data object - self._form = new FormData() - self._form.on('error', function (err) { - err.message = 'form-data: ' + err.message - self.emit('error', err) - self.abort() - }) - return self._form -} -Request.prototype.multipart = function (multipart) { - var self = this +/***/ 64193: +/***/ ((module) => { - self._multipart.onRequest(multipart) +"use strict"; - if (!self._multipart.chunked) { - self.body = self._multipart.body +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - return self -} -Request.prototype.json = function (val) { - var self = this - - if (!self.hasHeader('accept')) { - self.setHeader('accept', 'application/json') - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + composePaginateRest: () => composePaginateRest, + isPaginatingEndpoint: () => isPaginatingEndpoint, + paginateRest: () => paginateRest, + paginatingEndpoints: () => paginatingEndpoints +}); +module.exports = __toCommonJS(dist_src_exports); - if (typeof self.jsonReplacer === 'function') { - self._jsonReplacer = self.jsonReplacer - } +// pkg/dist-src/version.js +var VERSION = "9.2.2"; - self._json = true - if (typeof val === 'boolean') { - if (self.body !== undefined) { - if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { - self.body = safeStringify(self.body, self._jsonReplacer) - } else { - self.body = self._qs.rfc3986(self.body) - } - if (!self.hasHeader('content-type')) { - self.setHeader('content-type', 'application/json') - } - } - } else { - self.body = safeStringify(val, self._jsonReplacer) - if (!self.hasHeader('content-type')) { - self.setHeader('content-type', 'application/json') - } +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; } - - if (typeof self.jsonReviver === 'function') { - self._jsonReviver = self.jsonReviver + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) + return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; } - - return self -} -Request.prototype.getHeader = function (name, headers) { - var self = this - var result, re, match - if (!headers) { - headers = self.headers + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; } - Object.keys(headers).forEach(function (key) { - if (key.length !== name.length) { - return - } - re = new RegExp(name, 'i') - match = key.match(re) - if (match) { - result = headers[key] - } - }) - return result -} -Request.prototype.enableUnixSocket = function () { - // Get the socket & request paths from the URL - var unixParts = this.uri.path.split(':') - var host = unixParts[0] - var path = unixParts[1] - // Apply unix properties to request - this.socketPath = host - this.uri.pathname = path - this.uri.path = path - this.uri.host = host - this.uri.hostname = host - this.uri.isUnix = true -} - -Request.prototype.auth = function (user, pass, sendImmediately, bearer) { - var self = this - - self._auth.onRequest(user, pass, sendImmediately, bearer) - - return self + response.data.total_count = totalCount; + return response; } -Request.prototype.aws = function (opts, now) { - var self = this - - if (!now) { - self._aws = opts - return self - } - if (opts.sign_version === 4 || opts.sign_version === '4') { - // use aws4 - var options = { - host: self.uri.host, - path: self.uri.path, - method: self.method, - headers: self.headers, - body: self.body - } - if (opts.service) { - options.service = opts.service - } - var signRes = aws4.sign(options, { - accessKeyId: opts.key, - secretAccessKey: opts.secret, - sessionToken: opts.session +// pkg/dist-src/iterator.js +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) + return { done: true }; + try { + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + return { value: normalizedResponse }; + } catch (error) { + if (error.status !== 409) + throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } }) - self.setHeader('authorization', signRes.headers.Authorization) - self.setHeader('x-amz-date', signRes.headers['X-Amz-Date']) - if (signRes.headers['X-Amz-Security-Token']) { - self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token']) - } - } else { - // default: use aws-sign2 - var date = new Date() - self.setHeader('date', date.toUTCString()) - var auth = { - key: opts.key, - secret: opts.secret, - verb: self.method.toUpperCase(), - date: date, - contentType: self.getHeader('content-type') || '', - md5: self.getHeader('content-md5') || '', - amazonHeaders: aws2.canonicalizeHeaders(self.headers) - } - var path = self.uri.path - if (opts.bucket && path) { - auth.resource = '/' + opts.bucket + path - } else if (opts.bucket && !path) { - auth.resource = '/' + opts.bucket - } else if (!opts.bucket && path) { - auth.resource = path - } else if (!opts.bucket && !path) { - auth.resource = '/' - } - auth.resource = aws2.canonicalizeResource(auth.resource) - self.setHeader('authorization', aws2.authorization(auth)) - } - - return self -} -Request.prototype.httpSignature = function (opts) { - var self = this - httpSignature.signRequest({ - getHeader: function (header) { - return self.getHeader(header, self.headers) - }, - setHeader: function (header, value) { - self.setHeader(header, value) - }, - method: self.method, - path: self.path - }, opts) - debug('httpSignature authorization', self.getHeader('authorization')) - - return self -} -Request.prototype.hawk = function (opts) { - var self = this - self.setHeader('Authorization', hawk.header(self.uri, self.method, opts)) -} -Request.prototype.oauth = function (_oauth) { - var self = this - - self._oauth.onRequest(_oauth) - - return self + }; } -Request.prototype.jar = function (jar) { - var self = this - var cookies - - if (self._redirect.redirectsFollowed === 0) { - self.originalCookieHeader = self.getHeader('cookie') +// pkg/dist-src/paginate.js +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; } - - if (!jar) { - // disable cookies - cookies = false - self._disableCookies = true - } else { - var targetCookieJar = jar.getCookieString ? jar : globalCookieJar - var urihref = self.uri.href - // fetch cookie in the Specified host - if (targetCookieJar) { - cookies = targetCookieJar.getCookieString(urihref) + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; } - } - - // if need cookie and cookie is not empty - if (cookies && cookies.length) { - if (self.originalCookieHeader) { - // Don't overwrite existing Cookie header - self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies) - } else { - self.setHeader('cookie', cookies) + let earlyExit = false; + function done() { + earlyExit = true; } - } - self._jar = jar - return self -} - -// Stream API -Request.prototype.pipe = function (dest, opts) { - var self = this - - if (self.response) { - if (self._destdata) { - self.emit('error', new Error('You cannot pipe after data has been emitted from the response.')) - } else if (self._ended) { - self.emit('error', new Error('You cannot pipe after the response has been ended.')) - } else { - stream.Stream.prototype.pipe.call(self, dest, opts) - self.pipeDest(dest) - return dest + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; } - } else { - self.dests.push(dest) - stream.Stream.prototype.pipe.call(self, dest, opts) - return dest - } + return gather(octokit, results, iterator2, mapFn); + }); } -Request.prototype.write = function () { - var self = this - if (self._aborted) { return } - if (!self._started) { - self.start() - } - if (self.req) { - return self.req.write.apply(self.req, arguments) - } -} -Request.prototype.end = function (chunk) { - var self = this - if (self._aborted) { return } +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { + iterator +}); + +// pkg/dist-src/generated/paginating-endpoints.js +var paginatingEndpoints = [ + "GET /advisories", + "GET /app/hook/deliveries", + "GET /app/installation-requests", + "GET /app/installations", + "GET /assignments/{assignment_id}/accepted_assignments", + "GET /classrooms", + "GET /classrooms/{classroom_id}/assignments", + "GET /enterprises/{enterprise}/dependabot/alerts", + "GET /enterprises/{enterprise}/secret-scanning/alerts", + "GET /events", + "GET /gists", + "GET /gists/public", + "GET /gists/starred", + "GET /gists/{gist_id}/comments", + "GET /gists/{gist_id}/commits", + "GET /gists/{gist_id}/forks", + "GET /installation/repositories", + "GET /issues", + "GET /licenses", + "GET /marketplace_listing/plans", + "GET /marketplace_listing/plans/{plan_id}/accounts", + "GET /marketplace_listing/stubbed/plans", + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", + "GET /networks/{owner}/{repo}/events", + "GET /notifications", + "GET /organizations", + "GET /orgs/{org}/actions/cache/usage-by-repository", + "GET /orgs/{org}/actions/permissions/repositories", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/variables/{name}/repositories", + "GET /orgs/{org}/blocks", + "GET /orgs/{org}/code-scanning/alerts", + "GET /orgs/{org}/codespaces", + "GET /orgs/{org}/codespaces/secrets", + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", + "GET /orgs/{org}/copilot/billing/seats", + "GET /orgs/{org}/dependabot/alerts", + "GET /orgs/{org}/dependabot/secrets", + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", + "GET /orgs/{org}/events", + "GET /orgs/{org}/failed_invitations", + "GET /orgs/{org}/hooks", + "GET /orgs/{org}/hooks/{hook_id}/deliveries", + "GET /orgs/{org}/installations", + "GET /orgs/{org}/invitations", + "GET /orgs/{org}/invitations/{invitation_id}/teams", + "GET /orgs/{org}/issues", + "GET /orgs/{org}/members", + "GET /orgs/{org}/members/{username}/codespaces", + "GET /orgs/{org}/migrations", + "GET /orgs/{org}/migrations/{migration_id}/repositories", + "GET /orgs/{org}/organization-roles/{role_id}/teams", + "GET /orgs/{org}/organization-roles/{role_id}/users", + "GET /orgs/{org}/outside_collaborators", + "GET /orgs/{org}/packages", + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + "GET /orgs/{org}/personal-access-token-requests", + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", + "GET /orgs/{org}/personal-access-tokens", + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", + "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", + "GET /orgs/{org}/public_members", + "GET /orgs/{org}/repos", + "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", + "GET /orgs/{org}/secret-scanning/alerts", + "GET /orgs/{org}/security-advisories", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/teams/{team_slug}/discussions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/invitations", + "GET /orgs/{org}/teams/{team_slug}/members", + "GET /orgs/{org}/teams/{team_slug}/projects", + "GET /orgs/{org}/teams/{team_slug}/repos", + "GET /orgs/{org}/teams/{team_slug}/teams", + "GET /projects/columns/{column_id}/cards", + "GET /projects/{project_id}/collaborators", + "GET /projects/{project_id}/columns", + "GET /repos/{owner}/{repo}/actions/artifacts", + "GET /repos/{owner}/{repo}/actions/caches", + "GET /repos/{owner}/{repo}/actions/organization-secrets", + "GET /repos/{owner}/{repo}/actions/organization-variables", + "GET /repos/{owner}/{repo}/actions/runners", + "GET /repos/{owner}/{repo}/actions/runs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", + "GET /repos/{owner}/{repo}/actions/secrets", + "GET /repos/{owner}/{repo}/actions/variables", + "GET /repos/{owner}/{repo}/actions/workflows", + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", + "GET /repos/{owner}/{repo}/activity", + "GET /repos/{owner}/{repo}/assignees", + "GET /repos/{owner}/{repo}/branches", + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", + "GET /repos/{owner}/{repo}/code-scanning/alerts", + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + "GET /repos/{owner}/{repo}/code-scanning/analyses", + "GET /repos/{owner}/{repo}/codespaces", + "GET /repos/{owner}/{repo}/codespaces/devcontainers", + "GET /repos/{owner}/{repo}/codespaces/secrets", + "GET /repos/{owner}/{repo}/collaborators", + "GET /repos/{owner}/{repo}/comments", + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/commits", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", + "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", + "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", + "GET /repos/{owner}/{repo}/commits/{ref}/status", + "GET /repos/{owner}/{repo}/commits/{ref}/statuses", + "GET /repos/{owner}/{repo}/contributors", + "GET /repos/{owner}/{repo}/dependabot/alerts", + "GET /repos/{owner}/{repo}/dependabot/secrets", + "GET /repos/{owner}/{repo}/deployments", + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", + "GET /repos/{owner}/{repo}/environments", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", + "GET /repos/{owner}/{repo}/events", + "GET /repos/{owner}/{repo}/forks", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", + "GET /repos/{owner}/{repo}/invitations", + "GET /repos/{owner}/{repo}/issues", + "GET /repos/{owner}/{repo}/issues/comments", + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/issues/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", + "GET /repos/{owner}/{repo}/issues/{issue_number}/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", + "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", + "GET /repos/{owner}/{repo}/keys", + "GET /repos/{owner}/{repo}/labels", + "GET /repos/{owner}/{repo}/milestones", + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", + "GET /repos/{owner}/{repo}/notifications", + "GET /repos/{owner}/{repo}/pages/builds", + "GET /repos/{owner}/{repo}/projects", + "GET /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls/comments", + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", + "GET /repos/{owner}/{repo}/releases", + "GET /repos/{owner}/{repo}/releases/{release_id}/assets", + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", + "GET /repos/{owner}/{repo}/rules/branches/{branch}", + "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", + "GET /repos/{owner}/{repo}/secret-scanning/alerts", + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", + "GET /repos/{owner}/{repo}/security-advisories", + "GET /repos/{owner}/{repo}/stargazers", + "GET /repos/{owner}/{repo}/subscribers", + "GET /repos/{owner}/{repo}/tags", + "GET /repos/{owner}/{repo}/teams", + "GET /repos/{owner}/{repo}/topics", + "GET /repositories", + "GET /repositories/{repository_id}/environments/{environment_name}/secrets", + "GET /repositories/{repository_id}/environments/{environment_name}/variables", + "GET /search/code", + "GET /search/commits", + "GET /search/issues", + "GET /search/labels", + "GET /search/repositories", + "GET /search/topics", + "GET /search/users", + "GET /teams/{team_id}/discussions", + "GET /teams/{team_id}/discussions/{discussion_number}/comments", + "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /teams/{team_id}/discussions/{discussion_number}/reactions", + "GET /teams/{team_id}/invitations", + "GET /teams/{team_id}/members", + "GET /teams/{team_id}/projects", + "GET /teams/{team_id}/repos", + "GET /teams/{team_id}/teams", + "GET /user/blocks", + "GET /user/codespaces", + "GET /user/codespaces/secrets", + "GET /user/emails", + "GET /user/followers", + "GET /user/following", + "GET /user/gpg_keys", + "GET /user/installations", + "GET /user/installations/{installation_id}/repositories", + "GET /user/issues", + "GET /user/keys", + "GET /user/marketplace_purchases", + "GET /user/marketplace_purchases/stubbed", + "GET /user/memberships/orgs", + "GET /user/migrations", + "GET /user/migrations/{migration_id}/repositories", + "GET /user/orgs", + "GET /user/packages", + "GET /user/packages/{package_type}/{package_name}/versions", + "GET /user/public_emails", + "GET /user/repos", + "GET /user/repository_invitations", + "GET /user/social_accounts", + "GET /user/ssh_signing_keys", + "GET /user/starred", + "GET /user/subscriptions", + "GET /user/teams", + "GET /users", + "GET /users/{username}/events", + "GET /users/{username}/events/orgs/{org}", + "GET /users/{username}/events/public", + "GET /users/{username}/followers", + "GET /users/{username}/following", + "GET /users/{username}/gists", + "GET /users/{username}/gpg_keys", + "GET /users/{username}/keys", + "GET /users/{username}/orgs", + "GET /users/{username}/packages", + "GET /users/{username}/projects", + "GET /users/{username}/received_events", + "GET /users/{username}/received_events/public", + "GET /users/{username}/repos", + "GET /users/{username}/social_accounts", + "GET /users/{username}/ssh_signing_keys", + "GET /users/{username}/starred", + "GET /users/{username}/subscriptions" +]; - if (chunk) { - self.write(chunk) - } - if (!self._started) { - self.start() - } - if (self.req) { - self.req.end() - } -} -Request.prototype.pause = function () { - var self = this - if (!self.responseContent) { - self._paused = true - } else { - self.responseContent.pause.apply(self.responseContent, arguments) - } -} -Request.prototype.resume = function () { - var self = this - if (!self.responseContent) { - self._paused = false +// pkg/dist-src/paginating-endpoints.js +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); } else { - self.responseContent.resume.apply(self.responseContent, arguments) - } -} -Request.prototype.destroy = function () { - var self = this - this.clearTimeout() - if (!self._ended) { - self.end() - } else if (self.response) { - self.response.destroy() - } -} - -Request.prototype.clearTimeout = function () { - if (this.timeoutTimer) { - clearTimeout(this.timeoutTimer) - this.timeoutTimer = null + return false; } } -Request.defaultProxyHeaderWhiteList = - Tunnel.defaultProxyHeaderWhiteList.slice() - -Request.defaultProxyHeaderExclusiveList = - Tunnel.defaultProxyHeaderExclusiveList.slice() - -// Exports - -Request.prototype.toJSON = requestToJSON -module.exports = Request - - -/***/ }), - -/***/ 46624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const tls = __nccwpck_require__(24404); - -module.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => { - let timeout = false; - - let socket; - - const callback = async () => { - await socketPromise; - - socket.off('timeout', onTimeout); - socket.off('error', reject); - - if (options.resolveSocket) { - resolve({alpnProtocol: socket.alpnProtocol, socket, timeout}); - - if (timeout) { - await Promise.resolve(); - socket.emit('timeout'); - } - } else { - socket.destroy(); - resolve({alpnProtocol: socket.alpnProtocol, timeout}); - } - }; - - const onTimeout = async () => { - timeout = true; - callback(); - }; - - const socketPromise = (async () => { - try { - socket = await connect(options, callback); - - socket.on('error', reject); - socket.once('timeout', onTimeout); - } catch (error) { - reject(error); - } - })(); -}); - - -/***/ }), - -/***/ 9004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Readable = (__nccwpck_require__(12781).Readable); -const lowercaseKeys = __nccwpck_require__(9662); - -class Response extends Readable { - constructor(statusCode, headers, body, url) { - if (typeof statusCode !== 'number') { - throw new TypeError('Argument `statusCode` should be a number'); - } - if (typeof headers !== 'object') { - throw new TypeError('Argument `headers` should be an object'); - } - if (!(body instanceof Buffer)) { - throw new TypeError('Argument `body` should be a buffer'); - } - if (typeof url !== 'string') { - throw new TypeError('Argument `url` should be a string'); - } - - super(); - this.statusCode = statusCode; - this.headers = lowercaseKeys(headers); - this.body = body; - this.url = url; - } - - _read() { - this.push(this.body); - this.push(null); - } +// pkg/dist-src/index.js +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; } - -module.exports = Response; +paginateRest.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 97417: -/***/ ((__unused_webpack_module, exports) => { +/***/ 83044: +/***/ ((module) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -/* eslint-disable @typescript-eslint/strict-boolean-expressions */ -function parse(string, encoding, opts) { - var _opts$out; - - if (opts === void 0) { - opts = {}; - } - - // Build the character lookup table: - if (!encoding.codes) { - encoding.codes = {}; - - for (var i = 0; i < encoding.chars.length; ++i) { - encoding.codes[encoding.chars[i]] = i; - } - } // The string must have a whole number of bytes: - - - if (!opts.loose && string.length * encoding.bits & 7) { - throw new SyntaxError('Invalid padding'); - } // Count the padding bytes: - - - var end = string.length; - - while (string[end - 1] === '=') { - --end; // If we get a whole number of bytes, there is too much padding: - - if (!opts.loose && !((string.length - end) * encoding.bits & 7)) { - throw new SyntaxError('Invalid padding'); - } - } // Allocate the output: - - - var out = new ((_opts$out = opts.out) != null ? _opts$out : Uint8Array)(end * encoding.bits / 8 | 0); // Parse the data: - - var bits = 0; // Number of bits currently in the buffer - - var buffer = 0; // Bits waiting to be written out, MSB first - - var written = 0; // Next byte to write - - for (var _i = 0; _i < end; ++_i) { - // Read one character from the string: - var value = encoding.codes[string[_i]]; - - if (value === undefined) { - throw new SyntaxError('Invalid character ' + string[_i]); - } // Append the bits to the buffer: - - - buffer = buffer << encoding.bits | value; - bits += encoding.bits; // Write out some bits if the buffer has a byte's worth: - - if (bits >= 8) { - bits -= 8; - out[written++] = 0xff & buffer >> bits; - } - } // Verify that we have received just enough bits: - - - if (bits >= encoding.bits || 0xff & buffer << 8 - bits) { - throw new SyntaxError('Unexpected end of data'); - } - - return out; -} -function stringify(data, encoding, opts) { - if (opts === void 0) { - opts = {}; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - var _opts = opts, - _opts$pad = _opts.pad, - pad = _opts$pad === void 0 ? true : _opts$pad; - var mask = (1 << encoding.bits) - 1; - var out = ''; - var bits = 0; // Number of bits currently in the buffer - - var buffer = 0; // Bits waiting to be written out, MSB first - - for (var i = 0; i < data.length; ++i) { - // Slurp data into the buffer: - buffer = buffer << 8 | 0xff & data[i]; - bits += 8; // Write out as much as we can: - - while (bits > encoding.bits) { - bits -= encoding.bits; - out += encoding.chars[mask & buffer >> bits]; - } - } // Partial character: - - - if (bits) { - out += encoding.chars[mask & buffer << encoding.bits - bits]; - } // Add padding characters until we hit a byte boundary: - - - if (pad) { - while (out.length * encoding.bits & 7) { - out += '='; - } - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods +}); +module.exports = __toCommonJS(dist_src_exports); - return out; -} +// pkg/dist-src/version.js +var VERSION = "10.4.1"; -/* eslint-disable @typescript-eslint/strict-boolean-expressions */ -var base16Encoding = { - chars: '0123456789ABCDEF', - bits: 4 -}; -var base32Encoding = { - chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', - bits: 5 -}; -var base32HexEncoding = { - chars: '0123456789ABCDEFGHIJKLMNOPQRSTUV', - bits: 5 -}; -var base64Encoding = { - chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', - bits: 6 -}; -var base64UrlEncoding = { - chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', - bits: 6 -}; -var base16 = { - parse: function parse$1(string, opts) { - return parse(string.toUpperCase(), base16Encoding, opts); +// pkg/dist-src/generated/endpoints.js +var Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repositories/{repository_id}/environments/{environment_name}/variables" + ], + createOrUpdateEnvironmentSecret: [ + "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables" + ], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] }, - stringify: function stringify$1(data, opts) { - return stringify(data, base16Encoding, opts); - } -}; -var base32 = { - parse: function parse$1(string, opts) { - if (opts === void 0) { - opts = {}; - } - - return parse(opts.loose ? string.toUpperCase().replace(/0/g, 'O').replace(/1/g, 'L').replace(/8/g, 'B') : string, base32Encoding, opts); + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] }, - stringify: function stringify$1(data, opts) { - return stringify(data, base32Encoding, opts); - } -}; -var base32hex = { - parse: function parse$1(string, opts) { - return parse(string, base32HexEncoding, opts); + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] }, - stringify: function stringify$1(data, opts) { - return stringify(data, base32HexEncoding, opts); - } -}; -var base64 = { - parse: function parse$1(string, opts) { - return parse(string, base64Encoding, opts); + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] }, - stringify: function stringify$1(data, opts) { - return stringify(data, base64Encoding, opts); - } -}; -var base64url = { - parse: function parse$1(string, opts) { - return parse(string, base64UrlEncoding, opts); + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] }, - stringify: function stringify$1(data, opts) { - return stringify(data, base64UrlEncoding, opts); - } -}; -var codec = { - parse: parse, - stringify: stringify -}; - -exports.base16 = base16; -exports.base32 = base32; -exports.base32hex = base32hex; -exports.base64 = base64; -exports.base64url = base64url; -exports.codec = codec; - - -/***/ }), - -/***/ 21867: -/***/ ((module, exports, __nccwpck_require__) => { - -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - - -/***/ }), - -/***/ 15118: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* eslint-disable node/no-deprecated-api */ - - - -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } -} - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } -} - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer - - -/***/ }), - -/***/ 72043: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -;(function (sax) { // wrapper for non-node envs - sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } - sax.SAXParser = SAXParser - sax.SAXStream = SAXStream - sax.createStream = createStream - - // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. - // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), - // since that's the earliest that a buffer overrun could occur. This way, checks are - // as rare as required, but as often as necessary to ensure never crossing this bound. - // Furthermore, buffers are only tested at most once per write(), so passing a very - // large string into write() might have undesirable effects, but this is manageable by - // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme - // edge case, result in creating at most one complete copy of the string passed in. - // Set to Infinity to have unlimited buffers. - sax.MAX_BUFFER_LENGTH = 64 * 1024 - - var buffers = [ - 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', - 'procInstName', 'procInstBody', 'entity', 'attribName', - 'attribValue', 'cdata', 'script' - ] - - sax.EVENTS = [ - 'text', - 'processinginstruction', - 'sgmldeclaration', - 'doctype', - 'comment', - 'opentagstart', - 'attribute', - 'opentag', - 'closetag', - 'opencdata', - 'cdata', - 'closecdata', - 'error', - 'end', - 'ready', - 'script', - 'opennamespace', - 'closenamespace' - ] - - function SAXParser (strict, opt) { - if (!(this instanceof SAXParser)) { - return new SAXParser(strict, opt) - } - - var parser = this - clearBuffers(parser) - parser.q = parser.c = '' - parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH - parser.opt = opt || {} - parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags - parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' - parser.tags = [] - parser.closed = parser.closedRoot = parser.sawRoot = false - parser.tag = parser.error = null - parser.strict = !!strict - parser.noscript = !!(strict || parser.opt.noscript) - parser.state = S.BEGIN - parser.strictEntities = parser.opt.strictEntities - parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) - parser.attribList = [] - - // namespaces form a prototype chain. - // it always points at the current tag, - // which protos to its parent tag. - if (parser.opt.xmlns) { - parser.ns = Object.create(rootNS) - } - - // mostly just for error reporting - parser.trackPosition = parser.opt.position !== false - if (parser.trackPosition) { - parser.position = parser.line = parser.column = 0 - } - emit(parser, 'onready') - } - - if (!Object.create) { - Object.create = function (o) { - function F () {} - F.prototype = o - var newf = new F() - return newf - } - } - - if (!Object.keys) { - Object.keys = function (o) { - var a = [] - for (var i in o) if (o.hasOwnProperty(i)) a.push(i) - return a - } - } - - function checkBufferLength (parser) { - var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) - var maxActual = 0 - for (var i = 0, l = buffers.length; i < l; i++) { - var len = parser[buffers[i]].length - if (len > maxAllowed) { - // Text/cdata nodes can get big, and since they're buffered, - // we can get here under normal conditions. - // Avoid issues by emitting the text node now, - // so at least it won't get any bigger. - switch (buffers[i]) { - case 'textNode': - closeText(parser) - break - - case 'cdata': - emitNode(parser, 'oncdata', parser.cdata) - parser.cdata = '' - break - - case 'script': - emitNode(parser, 'onscript', parser.script) - parser.script = '' - break - - default: - error(parser, 'Max buffer length exceeded: ' + buffers[i]) - } + migrations: { + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" } - maxActual = Math.max(maxActual, len) - } - // schedule the next check for the earliest possible buffer overrun. - var m = sax.MAX_BUFFER_LENGTH - maxActual - parser.bufferCheckPosition = m + parser.position - } - - function clearBuffers (parser) { - for (var i = 0, l = buffers.length; i < l; i++) { - parser[buffers[i]] = '' - } - } - - function flushBuffers (parser) { - closeText(parser) - if (parser.cdata !== '') { - emitNode(parser, 'oncdata', parser.cdata) - parser.cdata = '' - } - if (parser.script !== '') { - emitNode(parser, 'onscript', parser.script) - parser.script = '' - } - } - - SAXParser.prototype = { - end: function () { end(this) }, - write: write, - resume: function () { this.error = null; return this }, - close: function () { return this.write(null) }, - flush: function () { flushBuffers(this) } - } - - var Stream - try { - Stream = (__nccwpck_require__(12781).Stream) - } catch (ex) { - Stream = function () {} - } - - var streamWraps = sax.EVENTS.filter(function (ev) { - return ev !== 'error' && ev !== 'end' - }) - - function createStream (strict, opt) { - return new SAXStream(strict, opt) - } - - function SAXStream (strict, opt) { - if (!(this instanceof SAXStream)) { - return new SAXStream(strict, opt) - } - - Stream.apply(this) - - this._parser = new SAXParser(strict, opt) - this.writable = true - this.readable = true - - var me = this - - this._parser.onend = function () { - me.emit('end') - } - - this._parser.onerror = function (er) { - me.emit('error', er) - - // if didn't throw, then means error was handled. - // go ahead and clear error, so we can write again. - me._parser.error = null - } - - this._decoder = null - - streamWraps.forEach(function (ev) { - Object.defineProperty(me, 'on' + ev, { - get: function () { - return me._parser['on' + ev] - }, - set: function (h) { - if (!h) { - me.removeAllListeners(ev) - me._parser['on' + ev] = h - return h - } - me.on(ev, h) - }, - enumerable: true, - configurable: false - }) - }) - } - - SAXStream.prototype = Object.create(Stream.prototype, { - constructor: { - value: SAXStream - } - }) - - SAXStream.prototype.write = function (data) { - if (typeof Buffer === 'function' && - typeof Buffer.isBuffer === 'function' && - Buffer.isBuffer(data)) { - if (!this._decoder) { - var SD = (__nccwpck_require__(71576).StringDecoder) - this._decoder = new SD('utf8') + ], + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" } - data = this._decoder.write(data) - } - - this._parser.write(data.toString()) - this.emit('data', data) - return true - } - - SAXStream.prototype.end = function (chunk) { - if (chunk && chunk.length) { - this.write(chunk) - } - this._parser.end() - return true - } - - SAXStream.prototype.on = function (ev, handler) { - var me = this - if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { - me._parser['on' + ev] = function () { - var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) - args.splice(0, 0, ev) - me.emit.apply(me, args) + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" } - } - - return Stream.prototype.on.call(me, ev, handler) - } - - // this really needs to be replaced with character classes. - // XML allows all manner of ridiculous numbers and digits. - var CDATA = '[CDATA[' - var DOCTYPE = 'DOCTYPE' - var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' - var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' - var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } - - // http://www.w3.org/TR/REC-xml/#NT-NameStartChar - // This implementation works on strings, a single character at a time - // as such, it cannot ever support astral-plane characters (10000-EFFFF) - // without a significant breaking change to either this parser, or the - // JavaScript language. Implementation of an emoji-capable xml parser - // is left as an exercise for the reader. - var nameStart = /[:_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 nameBody = /[:_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\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ - - var entityStart = /[#:_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 entityBody = /[#:_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\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ - - function isWhitespace (c) { - return c === ' ' || c === '\n' || c === '\r' || c === '\t' - } - - function isQuote (c) { - return c === '"' || c === '\'' - } - - function isAttribEnd (c) { - return c === '>' || isWhitespace(c) - } - - function isMatch (regex, c) { - return regex.test(c) - } - - function notMatch (regex, c) { - return !isMatch(regex, c) - } - - var S = 0 - sax.STATE = { - BEGIN: S++, // leading byte order mark or whitespace - BEGIN_WHITESPACE: S++, // leading whitespace - TEXT: S++, // general stuff - TEXT_ENTITY: S++, // & and such. - OPEN_WAKA: S++, // < - SGML_DECL: S++, // - SCRIPT: S++, //